python 之subprocess模块
1、将结果传给屏幕
2、将结果输给管道(读一次就没有了)
3、subprocess(可以扔到管道的东西)
4、远程执行DOS命令
1、服务端
from socket import * import subprocess ip_port = ("127.0.0.1",8080) back_log = 5 buffer_size = 1024 tcp_server = socket(AF_INET,SOCK_STREAM) tcp_server.bind(ip_port) tcp_server.listen(back_log) while 1: conn,adr = tcp_server.accept() print("新的客户端连接是%s,地址是%s"%(conn,adr)) while 1: try: cmd = conn.recv(buffer_size) if not cmd: break print("收到客户端的命令",cmd) res = subprocess.Popen(cmd.decode("utf-8"),shell= True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE) err = res.stderr.read() # if not err:#为空 if err:#有值 cmd = err else: cmd_res = res.stdout.read()#bite conn.send(cmd_res) except Exception as e: print(e) break conn.close()
2、客户端
from socket import * ip_port = ("127.0.0.1",8080) back_log = 5 buffer_size = 1024 tcp_client = socket(AF_INET,SOCK_STREAM) tcp_client.connect(ip_port) while 1: cmd = input(">>>>>>>>:").strip() if not cmd: continue if cmd == "quit": break tcp_client.send(cmd.encode("utf-8")) cmd_res = tcp_client.recv(buffer_size) print("命令的执行结果是",cmd_res.decode("gbk")) tcp_client.close()
5、补充:
# import os # ret = os.popen('ls').read() # print(ret) import subprocess # 内置模块 和os模块的功能有相似之处 # 能执行操作系统的命令的功能 ret = subprocess.Popen('dir', # 要执行的命令 shell=True, # 表示要执行的是一条系统命令 stdout=subprocess.PIPE, # 存储执行结果的正常信息 stderr=subprocess.PIPE) # 存储执行结果的错误信息 print('stdout : ',ret.stdout.read().decode('gbk')) print('stderr : ',ret.stderr.read().decode('gbk'))