相关的模块名
1.subprocess模块:执行系统模块
subprocess.Popen():调用当前系统来执行命令
stdout:标准正确的输出
stderr:错误的输出
stdin:输入
shell = True ,系用解释器
subprocess。PIPE: 就是一个管道
2.struct模块
struct.pack: 打包成一个bates类型
struct.unpack : 解包,解包一个bates的类型
struct的一些方法:
详细网站:http://www.cnblogs.com/coser/archive/2011/12/17/2291160.html
实例1:
服务端
1 import socket 2 import subprocess 3 import struct 4 phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 5 phone.bind(('127.0.0.1',8080)) 6 phone.listen(10) 7 while True: 8 conn,addr=phone.accept() 9 print(addr[0:2]) 10 while True: 11 try: 12 msg=conn.recv(1024).decode('utf-8') 13 obj=subprocess.Popen(msg,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 14 stdout=obj.stdout.read() 15 stderr=obj.stderr.read() 16 tes=struct.pack('i',len(stdout)+len(stderr)) 17 conn.send(tes) 18 conn.send(stdout) 19 conn.send(stderr) 20 except Exception: 21 break 22 conn.close() 23 phone.close()
客户端:
1 import socket 2 import struct 3 phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 4 phone.connect(('127.0.0.1',8080)) 5 while True: 6 msg=input('>>>:').strip() 7 phone.send(msg.encode('utf-8')) 8 if not msg:continue 9 tes=phone.recv(4) 10 tes_size=struct.unpack('i',tes)[0] 11 print(tes_size) 12 msg_data_1=b'' 13 data_size=0 14 while data_size<tes_size: 15 msg_data=phone.recv(1024) 16 msg_data_1+=msg_data 17 data_size+=len(msg_data) 18 19 print(msg_data_1.decode('gbk')) 20 phone.close()