本章内容
1.命令模块
2.面向对象 封装 继承 多态
3.反射
4.异常处理
5.socket
1.命令模块
import os os.system("ls") a=os.system("ls")
保存命令执行结果
popen a=os.popen("df").read() print(a)
subprocess执行复杂命令 | 保存执行结果 | 返回执行结果
(run方法python3.5才有的) import subprocess subprocess.run("df -h |grep sda",shell=True) a=subprocess.run("df -h |grep sda",shell=True)
查看命令执行结果
poll() 查看命令执行中或执行完毕(执行中返回None 执行完返回) stdout=subprocess.PIPE 查看命令标准输出 stderr=subprocess.PIPE 查看命令标准错误输出 >>> res=subprocess.Popen("sleep 10;echo 'hello':",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> print(res.poll()) None >>> print(res.poll()) 0 >>> >>> res=subprocess.Popen("sleep 10;ech 'hello':",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> print(res.poll()) 127
getstatusoutput执行命令返回结果和状态
>>> subprocess.getstatusoutput("df -h |grep sda") (0, '/dev/sda2 44G 2.3G 40G 6% /') >>> subprocess.getstatusoutput("df -h |grep zz") (1, '')
wait()等待命令只想完毕
>>> res=subprocess.Popen("sleep 10;echo 'hello':",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> res.wait() 0 >>>
terminate()停止令执行
>>> res=subprocess.Popen("sleep 10;echo 'hello':",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> res.terminate() >>> res.stdout.read() b'' >>> 传递密码 subprocess.run("echo "123" | sudo -S yum install vim",shell=True)
2.面向对象
def person(name, age, sex, job): def walk(p): print("person %s is walking..." % p['name']) data = { 'name': name, 'age': age, 'sex': sex, 'job': job, 'walk': walk } return data def dog(name, dog_type): def bark(d): print("dog %s:wang.wang..wang..." % d['name']) data = { 'name': name, 'type': dog_type, 'bark': bark } return data d1 = dog("李磊","京巴") p1 = person("严帅",36,"F","运维") p1['walk'](p1)
class dog(object): def __init__(self,name): #构造方法 self.name=name #属性 成员变量 def sayhi(self): #方法 print("hello word",self.name) d1=dog("abc") #实例 d1.sayhi()
class dog(object): def __init__(self,name): #构造方法 self.name=name def sayhi(self): #类方法 print("hello word",self.name) def eat(self,food): print("%s asd %s " %(self.name,food)) d1=dog("abc") #实例 d1.eat('as')
class Role(object): def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...",self.weapon) def buy_gun(self,gun_name): print("just bought %s" % gun_name) self.weapon=gun_name r2 = Role('Jack', 'terrorist','B22') r2.buy_gun('B51') print(r2.weapon)
2.1封装(私有属性)
class Role(object): def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart= 'normal' #私有属性 def get_heart(self): #访问私有属性只读 return self.__heart def shot(self): print("shooting...") self.__heart='die' print(self.__heart) r2 = Role('Jack', 'terrorist','B22') print(r2.name) print(self.__heart) r2.shot() r2.get_heart() #访问私有属性只读 print(r2._Role__heart) #强制访问私有属性
2.2封装(公有属性)
class Role(object): nationality = 'JP' #公有属性 def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart= 'normal' def shot(self): print("shooting...") self.__heart='die' print(self.__heart) r1 = Role('Tom', 'terrorist','B51') r2 = Role('Jack', 'terrorist','B22') print(r1.nationality) print(Role.nationality) #修改 # Role.nationality='US' # r1.nationality='CN' # print(r1.nationality) # print(Role.nationality)
class Role(object): nationality = 'JP' def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart= 'normal' def shot(self): print("shooting...") self.__heart='die' print(self.__heart) r1 = Role('Tom', 'terrorist','B51') r2 = Role('Jack', 'terrorist','B22') def shot2(self): print("run my own shot method",self.name) #设置私有方法 r1.shot=shot2 r1.shot(r1)
类的析构方法(做一些程序收尾的工作)
class Role(object): nationality = 'JP' def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart= 'normal' def shot(self): print("shooting...") self.__heart='die' print(self.__heart) def __del__(self): print("del .......run") r1=Role('hantao','tufei','b22')
2.3继承
class Person(object): def __init__(self,name,age): self.name=name self.age=age self.sex="noraml" def talk(self): print("person is talking...l") class BlackPerson(Person): #先继承 再构造 def __init__(self,name,age,strength): #构造 Person.__init__(self,name,age) #传递 self.strength = strength #构造 print(self.name,self.age,self.sex) def talk(self): #构造 Person.talk(self) print("blck person is blaba **") b=BlackPerson("wei er smith",30,"strong") b.talk()
class SchoolMember(object): '''学校成员基类''' member = 0 def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex self.enroll() def enroll(self): '''注册''' print("just enrolled a new school member [%s]"% self.name) SchoolMember.member +=1 def tell(self): print('------info:%s--------'%self.name) for k,v in self.__dict__.items(): print(k,v) def __del__(self): print("开出[%s]..."% self.name) SchoolMember.member -=1 class Teacher(SchoolMember): #类 '''讲师类''' def __init__(self,name,age,sex,salary,course): #构造方法 SchoolMember.__init__(self,name,age,sex) self.salary = salary #属性 self.course = course def teaching(self): #方法 print("Teacher [%s] is teaching [%s]" % (self.name,self.course)) class Student(SchoolMember): def __init__(self,name,age,sex,course,tuition): SchoolMember.__init__(self,name,age,sex) self.course = course self.tuition = tuition self.amount = 0 def pay_tuition(self,amount): print("student [%s] has just paied [%s]" %(self.name,amount)) self.amount += amount t1 = Teacher("Wusir",28,"F*M",3000,"Python") #属性 对象 s1 = Student("HaiTao",38,"N/A","PYS15",30000) s2 = Student("LIChuang",12,"M","PYS15",11000) print(SchoolMember.member) t1.tell() s2.tell()
新式类写法
class SchoolMember(object): '''学校成员基类''' member = 0 def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex self.enroll() def enroll(self): '''注册''' print("just enrolled a new school member [%s]"% self.name) SchoolMember.member +=1 def tell(self): print('------info:%s--------'%self.name) for k,v in self.__dict__.items(): print(k,v) def __del__(self): print("开出[%s]..."% self.name) SchoolMember.member -=1 class Teacher(SchoolMember): '''讲师类''' def __init__(self,name,age,sex,salary,course): #SchoolMember.__init__(self,name,age,sex) super(Teacher,self).__init__(name,age,sex) #新式类写法 self.salary = salary self.course = course def teaching(self): print("Teacher [%s] is teaching [%s]" % (self.name,self.course)) t1 = Teacher("Wusir",28,"F*M",3000,"Python") print(SchoolMember.member) t1.tell()
多继承
class SchoolMember(object): '''学校成员基类''' member = 0 def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex self.enroll() def enroll(self): '''注册''' print("just enrolled a new school member [%s]"% self.name) SchoolMember.member +=1 def tell(self): print('------info:%s--------'%self.name) for k,v in self.__dict__.items(): print(k,v) def __del__(self): print("开出[%s]..."% self.name) SchoolMember.member -=1 class Schol(object): def open_branch(self,addr): print("test",addr) class Teacher(SchoolMember,Schol): ###### pass t1 = Teacher("Wusir",28,"F*M") t1.open_branch("zhang")
新式类继承vs经典继承
广度查找从左到右---深度查找从下到上
python3 新式类继承和经典集成都是广度查找
python2 经典继承深度查找--新式类继承广度查找
强制重构
class Ainmal(object): def __init__(self,name): self.name = name def talk(self): raise NotImplementedError("Subclass must implement abstract method") class Cat(Ainmal): def talk(self): print("ok") class Dog(Ainmal): def talk(self): return "Woof! Woof!" d = Dog('d1') c = Cat("c1") c.talk() d.talk()
2.4多态
#模拟多态 class Ainmal(object): def __init__(self,name): self.name = name def talk(self): raise NotImplementedError("Subclass must implement abstract method") class Cat(Ainmal): def talk(self): print("ok") class Dog(Ainmal): def talk(self): return "Woof! Woof!" d = Dog('d1') c = Cat("c1") def animal_talk(obj): print(obj.talk()) animal_talk(d) animal_talk(c)
2.5面向对象总结
self就是调用当前方法的发放的对象
静态字段使用场景 每个对象保存的东西相同时 可以使用静态字段
class Foo(object): '''静态字段 共有属性''' country = '中国' def __init__(self,name,count): '''普通字段 普通属性''' self.name = name self.count = count def bar(self): print("asd",self.name,self.count,self.country) obj1 = Foo('河南',100000) obj1.bar() obj2 = Foo('山东',10000) obj2.bar()
继承
class F1: def __init__(self,n): self.N = n print("F1") class F2: def __init__(self,arg1): self.a = arg1 print("F2") class F3: def __init__(self,arg2): self.b = arg2 print("F3") o1 = F1('alex') o2 = F2(o1) o3 = F3(o2) print(o3.b.a.N)
class F1: def __init__(self): print("F1") def a1(self): print("F1a1") def a2(self): print("F1a2") class F2(F1): def __init__(self): print("F2") def a1(self): self.a2() print("F2a1") def a2(self): print("F2a2") class F3(F2): def __init__(self): print("F3") def a2(self): print("F3a2") obj = F3() obj.a1()
静态方法 保存在类中 调用者类 无需创建对象 可以有任意个参数
class F1: @staticmethod def a1(a1,a2): print('alex') F1.a1(1,2)
什么时候适合用面向对象
-如果多个函数需传入多个共同的参数时
-根据一个模板创建某些东西
-应用场景
class SSH: def __init__(self,host,port,pwd,username): self.host = ... def connection(self): #去创建链接 self.comm = 和服务器创建的链接对象() def close(self): #关闭 self.conn.关闭 def upload(self): self.conn 使用链接上传文件 def cmd(self): self.conn() 使用连接执行文件 obj = SSH(....) obj.connection() obj.upload() obj.close()
staticmethod静态方法
静态方法 和普通函数一样 只是属于类下面的一个函数 不可以调用类变量 class Dog(object): def __init__(self,name): self.name = name @staticmethod def eat(self): print("%s is eating %s" %(self.name,'aa')) def talk(self): print("%s is talking"% self.name) d = Dog("ChenRonghua") d.eat(d) d.talk()
classmethod类方法
类方法 只可以访问类变量 不可以访问实例变量 class Dog(object): name = "huazai" def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating " %(self.name)) def talk(self): print("%s is talking"% self.name) d = Dog("ChenRonghua") d.eat() d.talk()
property属性方法
属性方法 把一个方法变成属性 class Dog(object): def __init__(self,name): self.name = name self.__food = None @property def eat(self): print("%s is eating " %(self.name,self.__food)) @eat.setter def eat(self,food): self.__food = food print("%s is eating %s" % (self.name,food)) @eat.deleter def eat(self): del self.__food print("删除完了") d = Dog("ChenRonghua") d.eat='abc' del d.eat d.eat
属性方法应用场景
1. 连接航空公司API查询 2. 对查询结果进行解析 3. 返回结果给你的用户 class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("check flight %s status "% self.flight_name) return 1 @property def flight_status(self): status = self.checking_status() if status == 0: print("flight got cancleed") elif status == 1: print("flight is arrived") elif status == 2: print("flight has departuerd already") else: print("canot confirm the dlight status pleass check later") @flight_status.setter def flight_status(self,status): print("flight %s has changed status to %s "%(self.flight_name,status)) f = Flight("CA980") f.flight_status f.flight_status = 2
__doc__打印描述信息
class Foo: '''描述信息''' def func(self) pass print(Foo.__doc__)
__module__,__class__
__module__ 表示当前操作的对象在那个模块 __class__ 表示当前操作的对象的类是什么 class c: def __init__(self): self.name = 'wupeiqi' from test import c obj = c() print(obj.__module__) print(obj.__class__)
__call__
__call__ `对象后面加括号 执行 class Foo: def __init__(self): pass def __call__(self,*args,**kwargs): print('__call__') obj = Foo() obj()
__dict__
__dict__ 查看类或对象中的所有成员 class Province: country = 'china' def __init__(self,name,count): self.name = name self.count = count def func(self,*args,**kwargs): print('func') print (Province.__dict__) 获取类的成员,即:静态字段、方法 obj = Province("abc",1000) print(obj.__dict__) 获取 对象obj 的成员
__str__
如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值 class Foo: def __str__(self): return "alex li" obj = Foo() print(obj)
__getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据 class Foo(object): def __getitem__(self,key): print('__gettiem__',key) def __setitem__(self,key,value): print('__setitem__',key,value) def __delitem__(self,key): print("__delitem",key) obj = Foo() result = obj['k1'] 自动触发执行 __getitem_ obj['k2'] = 'alex' 自动触发执行 __setitem__ del obj['k1']
3.反射
hasattr- getattr
class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("%s is eating ..%s"%(self.name,food)) d = Dog("abc") choice = input(">>:").strip() if hasattr(d,choice): #判断方法是否存在 返回True或False func = getattr(d,choice) #存在就执行 func("kk") #传参数
setattr
def bulk(self): print("%s is telling.."%self.name) class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("%s is eating ..%s"%(self.name,food)) d = Dog("abc") choice = input(">>:").strip() if hasattr(d,choice): func = getattr(d,choice) func("kk") setattr(d,choice,"rh") #修改属性的参数 print(d.name) else: setattr(d,choice,bulk) #如果输入的方法不存在 全部执行 bulk方法 d.talk(d) setattr(d,choice,22) #如果输入的属性不存在 就返回22 print(getattr(d,choice))
如果输入的方法不存在 全部执行 bulk方法 if hasattr(d,choice): getattr(d,choice) else: setattr(d,choice,bulk) func = getattr(d,choice) func(d) 如果输入的属性不存在 就返回None if hasattr(d,choice): getattr(d,choice) else: setattr(d,choice,None) v=getattr(d,choice) print(v)
delattr
delattr def bulk(self): print("%s is telling.."%self.name) class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("%s is eating ..%s"%(self.name,food)) d = Dog("abc") choice = input(">>:").strip() if hasattr(d,choice): #输入的方法存在就删出 delattr(d,choice)
4.异常处理
try: names[3] except Exception as e: print("错误",e) names = [] try: names[3] except IndexError as e: print("没有这个index",e) try: open(test.txt) #尝试执行代码 except (KeyError,IndexError) as e: #如果报错打印下面信息 print("没有这个 key",e) except Exception as e: print("未知错误",e) else: print("一切正常") finally: print("不管有没有错,都执行")
自定义错误
class AlexError(Exception): def __init__(self,msg): self.message = msg try: raise AlexError('自定义错误') except AlexError as e: print(e)
1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x 2 IOError 输入/输出异常;基本上是无法打开文件 3 ImportError 无法引入模块或包;基本上是路径问题或名称错误 4 IndentationError 语法错误(的子类) ;代码没有正确对齐 5 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] 6 KeyError 试图访问字典里不存在的键 7 KeyboardInterrupt Ctrl+C被按下 8 NameError 使用一个还未被赋予对象的变量 9 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) 10 TypeError 传入对象类型与要求的不符合 11 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 12 导致你以为正在访问它 13 ValueError 传入一个调用者不期望的值,即使值的类型是正确的 14 15 常用异常
1 ArithmeticError 2 AssertionError 3 AttributeError 4 BaseException 5 BufferError 6 BytesWarning 7 DeprecationWarning 8 EnvironmentError 9 EOFError 10 Exception 11 FloatingPointError 12 FutureWarning 13 GeneratorExit 14 ImportError 15 ImportWarning 16 IndentationError 17 IndexError 18 IOError 19 KeyboardInterrupt 20 KeyError 21 LookupError 22 MemoryError 23 NameError 24 NotImplementedError 25 OSError 26 OverflowError 27 PendingDeprecationWarning 28 ReferenceError 29 RuntimeError 30 RuntimeWarning 31 StandardError 32 StopIteration 33 SyntaxError 34 SyntaxWarning 35 SystemError 36 SystemExit 37 TabError 38 TypeError 39 UnboundLocalError 40 UnicodeDecodeError 41 UnicodeEncodeError 42 UnicodeError 43 UnicodeTranslateError 44 UnicodeWarning 45 UserWarning 46 ValueError 47 Warning 48 ZeroDivisionError 49 50 更多异常
5.socket
#服务端 import socket server = socket.socket() #声明socket类型 server.bind(('localhost',6969)) #设置侦听端口 server.listen() #开始侦听 print("开始等待:") conn,addr = server.accept() #等待数据 #conn是客户端链接过来的一个实例,addr是ip和port print(conn,addr) print("等待来了") data = conn.recv(1024) #设置接受数据大小 print("recv:",data.decode('utf-8')) conn.send(data.upper()) #再发送给客户端 server.close() #关闭 #客户端 import socket client = socket.socket() #声明socket类型和socket链接对象(ip.port) client.connect(('localhost',6969)) #链接端口 client.send("你好".encode('utf-8')) #发送数据,转码utf8 # client.send(b"Hello World!") data = client.recv(1024) #设置接受数据大小 print("recv",data.decode('utf-8')) #打印数据 client.close() #关闭连接
#!/usr/bin/env python # _*_ encoding:utf-8 _*_ #服务器端 import socket server = socket.socket() server.bind(('localhost',7000)) server.listen() print("开始等待:") while True: conn,addr = server.accept() print(conn,addr) print("等待来了") while True: data = conn.recv(1024) print("recv:",data) if not data: print("client not data") break conn.send(data.upper()) server.close() ------------------ #!/usr/bin/env python # _*_ encoding:utf-8 _*_ #客户端 import socket client = socket.socket() client.connect(('localhost',7000)) while True: msg = input(">>:").strip() if len(msg) == 0:continue client.send(msg.encode("utf-8")) data = client.recv(1024) print("recv",data.decode()) client.close()
1 #!/usr/bin/env python 2 # _*_ encoding:utf-8 _*_ 3 4 #客户端 5 import socket 6 7 client = socket.socket() 8 client.connect(('localhost',7000)) 9 10 while True: 11 msg = input(">>:").strip() 12 if len(msg) == 0:continue 13 client.send(msg.encode("utf-8")) 14 data = client.recv(1024) 15 print("recv",data.decode()) 16 17 client.close() 18 19 --------------------------------- 20 21 # _*_ encoding:utf-8 _*_ 22 23 #服务器端 24 25 import socket 26 import os 27 import subprocess 28 29 server = socket.socket() 30 server.bind(('localhost',7777)) 31 server.listen() 32 33 print("开始等待:") 34 while True: 35 conn,addr = server.accept() 36 37 print(conn,addr) 38 print("等待来了") 39 40 while True: 41 data = conn.recv(1024) 42 print(data) 43 if not data: 44 print("client not data") 45 break 46 res=os.popen(data).read() 47 conn.sendall(res) 48 49 server.close()
1 #!/usr/bin/env python 2 # _*_ encoding:utf-8 _*_ 3 4 import socket 5 6 client = socket.socket() #声明socket类型和socket链接对象(ip.port) 7 client.connect(('localhost',7777)) #链接端口 8 9 f = open("ac.av","wb") 10 while True: 11 msg = input(">>:").strip() 12 if len(msg) == 0:continue 13 client.send(msg.encode('utf-8')) #发送数据,转码utf8 14 data = client.recv(102400) #设置接受数据大小 15 f.write(data) 16 f.flush() 17 18 client.close() #关闭连接 19 --------------------- 20 21 #服务器端 22 23 import socket 24 import os 25 26 server = socket.socket() 27 server.bind(('localhost',7777)) 28 server.listen() 29 30 print("开始等待:") 31 while True: 32 conn,addr = server.accept() 33 34 print(conn,addr) 35 print("等待来了") 36 37 while True: 38 data = conn.recv(102400) 39 print(data) 40 if not data: 41 print("client not data") 42 break 43 #res=os.popen(data).read() 44 #conn.sendall(res) 45 f = open('abc.wmv') 46 data = f.read() 47 conn.sendall(data) 48 49 server.close()
简单接受发送
1 #server 2 3 import socket 4 import json 5 6 s = socket.socket() 7 s.bind(('localhost',9000)) 8 9 s.listen(5) 10 11 while True: 12 conn,client_addr = s.accept() 13 print('got a new conn:',client_addr) 14 while True: 15 data = conn.recv(1024) 16 print("recv data:",data) 17 data = json.loads(data.decode()) 18 19 if data.get("action") is not None: 20 if data['action'] == 'put': 21 file_obj = open(data['filename'],'wb') 22 received_size = 0 23 24 while received_size < data['size']: 25 recv_data = conn.recv(4096) 26 file_obj.write(recv_data) 27 received_size += len(recv_data) 28 print(data['size'],received_size) 29 else: 30 print("---successfully received file [%s]--",data['filename']) 31 file_obj.close() 32 33 elif data['action'] == 'get': 34 pass 35 36 37 38 39 40 41 42 #client 43 44 import socket 45 import os 46 import json 47 48 client = socket.socket() 49 client.connect(('localhost',9000)) 50 51 while True: 52 choice = input(">>>").strip() 53 if len(choice) == 0:continue 54 cmd_list = choice.split() 55 if cmd_list[0] == "put": 56 if len(cmd_list) == 1: 57 print("no filename folliws after put cmd") 58 continuelename 59 fi = cmd_list[1] 60 if os.path.isfile(filename): 61 file_obj = open(filename,'rb') 62 base_filename = filename.split("/")[-1] 63 print(base_filename,os.path.getsize(filename)) 64 data_header = { 65 "action":"put", 66 "filename":base_filename, 67 "size":os.path.getsize(filename) 68 } 69 client.send(json.dumps(data_header).encode()) 70 71 for line in file_obj: 72 client.send(line) 73 print("-------file is donw-------") 74 75 76 else: 77 print("file is not valid") 78 continue 79 elif cmd_list[0] == "get": 80 pass
更多功能
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
参数一:地址簇 socket.AF_INET IPv4(默认) socket.AF_INET6 IPv6 socket.AF_UNIX 只能够用于单一的Unix系统进程间通信 参数二:类型 socket.SOCK_STREAM 流式socket , for TCP (默认) socket.SOCK_DGRAM 数据报式socket , for UDP socket.SOCK_RAW 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。 socket.SOCK_RDM 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。 socket.SOCK_SEQPACKET 可靠的连续数据包服务 参数三:协议 0 (默认)与特定的地址家族相关的协议,如果是 0 ,则系统就会根据地址格式和套接类别,自动选择一个合适的协议
sk.bind(address) s.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。 sk.listen(backlog) 开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。 backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5 这个值不能无限大,因为要在内核中维护连接队列 sk.setblocking(bool) 是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。 sk.accept() 接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。 接收TCP 客户的连接(阻塞式)等待连接的到来 sk.connect(address) 连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。 sk.connect_ex(address) 同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061 sk.close() 关闭套接字 sk.recv(bufsize[,flag]) 接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。 sk.recvfrom(bufsize[.flag]) 与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。 sk.send(string[,flag]) 将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。 sk.sendall(string[,flag]) 将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。 内部通过递归调用send,将所有内容发送出去。 sk.sendto(string[,flag],address) 将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。 sk.settimeout(timeout) 设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s ) sk.getpeername() 返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。 sk.getsockname() 返回套接字自己的地址。通常是一个元组(ipaddr,port) sk.fileno()
class socketserver.ForkingTCPServer tcp 进程 class socketserver.ForkingUDPServer udp 进程 class socketserver.ThreadingTCPServer tcp 线程 class socketserver.ThreadingUDPServer udp线程
多线程接受数据
#服务端 import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): while True: self.data = self.request.recv(1024).strip() print(self.client_address[0]) print(self.data) self.request.sendall(self.data.upper()) if __name__ == '__main__': HOST,PORT = "localhost",9000 server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler) server.serve_forever() #客户端 import socket import os import json client = socket.socket() client.connect(('localhost',9000)) while True: choice = input("输入>>>:").strip() if len(choice) == 0:continue client.send(choice.encode()) recv = client.recv(1024) print("recviver:",recv.decode())
避免断开报错
客户端断开地址会报错地址在占用 因为服务端没有释放ip 添加此内容就会释放ip
import socket server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
简单线程
import threading import time def run(n): time.sleep(1) print("run....",n) for i in range(10): t = threading.Thread(target=run,args=(i,)) t.start()
class_system
bin/start.py
1 import os 2 import sys 3 import platform 4 5 if platform.system() == "Windows": 6 BASE_DIR = "\".join(os.path.abspath(os.path.dirname(__file__)).split("\")[:-1]) 7 8 else: 9 BASE_DIR = "/".join(os.path.abspath(os.path.dirname(__file__)).split("/")[:-1]) 10 11 12 from core import main 13 from conf import settings 14 15 if __name__ == '__main__': 16 obj = main.Manage_center() 17 obj.run()
conf/settings.py
1 #!/usr/bin/python env 2 # _*_ encoding:utf-8 _*_ 3 4 import os 5 import sys 6 import platform 7 8 if platform.system() == "Windows": 9 BASE_DIR = "\".join(os.path.abspath(os.path.dirname(__file__)).split("\")[:-1]) 10 database_path = os.path.join(BASE_DIR,'database') 11 12 else: 13 BASE_DIR = "/".join(os.path.abspath(os.path.dirname(__file__)).split("/")[:-1]) 14 database_path = os.path.join(BASE_DIR,"database") 15 16 school_db_file = os.path.join(database_path,"school")
core/main.py
1 import os 2 import sys 3 import shelve 4 from conf import settings 5 from modules.school import School 6 7 class Manage_center(object): 8 def __init__(self): 9 pass 10 11 def run(self): 12 while True: 13 print(" 欢迎进入CLASS_SYSTEM系统 " 14 "1.学生视图 " 15 "2.教师视图 " 16 "3.学校视图 " 17 "q 推出") 18 user_choice = input("