python subprocess 小例子
#服务端import socketimport osimport subprocessphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print('进行绑定,监听')phone.bind(('127.0.0.1', 8080))phone.listen(5)
def cmd(cmdlist): obj=subprocess.Popen( cmdlist, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
stdout_res=obj.stdout.read() stderr_res=obj.stderr.read()
return stdout_res+stderr_res#假如不写成方法,这里可以分成两次发送过去,更加节省内存
while True: conn, add = phone.accept() print('建立连接')
while True: try: msg = conn.recv(1024) if not len(msg): break
print('执行命令') print(msg) #os.system(msg.decode(encoding='utf-8'))
stdout_res=cmd(msg.decode(encoding='utf-8')) print('发送消息') conn.send(stdout_res) except Exception: break
conn.close()phone.close()
#客户端
import socket
st = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
st.connect(('127.0.0.1', 8080))while True: msg=input('请输入cmd 命令').strip() print('发送消息') if not len(msg):continue
st.send(msg.encode(encoding='utf-8')) data=st.recv(1024) print(data.decode('gbk'))
st.close()
#服务端
# import socketserver### class Myhandler(socketserver.BaseRequestHandler):# def Hadler(self):# print('连接建立成功')# while True:# try:# data = self.request.recv(1024)# if not len(data): break# self.request.send(data)## except ConnectionResetError:# break## self.request.close()### if __name__ == '__main__':# print('开始启动')# st = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), Myhandler, bind_and_activate=True)# print('开始建立连接')# st.serve_forever() # 提供无限循环,循环建立链接# # 每建立链接,就会启动一个线程,专门与刚刚# # 建立好的链接做通信循环# # 调用myhandler类产生一个对象,条用该对象下的handler方法,专门与刚刚建立好的# # 连接做通信循环
import socketserverimport jsonimport structimport subprocessimport os
class MyHandler(socketserver.BaseRequestHandler): def handle(self): # 通信循环 while True: try: cmd = self.request.recv(1024) if len(cmd) == 0: break else: cmd = cmd.decode(encoding='utf-8')
if cmd == 'get': path = 'file.txt' if not os.path.exists(path): raise ValueError('没有文件') total_size = os.path.getsize(filename=path) print(total_size) import hashlib with open(path, 'rb') as f: for line in f: line hashlib_value = 'xxxx' else: obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s_out = obj.stdout.read() s_err = obj.stderr.read() total_size = len(s_out) + len(s_err) path = None hashlib_value = '你大爷'
header_dic = { 'file_name': path, 'total_size': total_size, 'hashlib': hashlib_value } header_json = (json.dumps(header_dic)).encode(encoding='utf-8') header_len = struct.pack('i', len(header_json)) print('header_len:%s' % header_len)
# print(header_len) self.request.send(header_len) # print(header_json) self.request.send(header_json)
if cmd == 'get': with open(path, 'rb') as f: for line in f: # print(line) self.request.send(line) else: # print('cmd') self.request.send(s_out) self.request.send(s_err)
except ConnectionResetError: break
self.request.close()
if __name__ == "__main__": s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyHandler, bind_and_activate=True) s.serve_forever()
#客户端
# from socket import *## socket_client = socket(AF_INET, SOCK_STREAM)# print('进行连接')# socket_client.connect(('127.0.0.1', 8080))# print('连接成功')# while True:# msg = input('请输入')# if not len(msg): continue# socket_client.send(msg.encode(encoding='utf-8'))# data =socket_client.recv(1024)# print(data.decode(encoding='utf-8'))## socket_client.close()
import socket, struct, json, hashlib
st = socket.socket(socket.AF_INET, socket.SOCK_STREAM)st.connect(('127.0.0.1', 8080))
def get_file(st): data = st.recv(4) print(data) data = struct.unpack('i', data)[0] header_json = json.loads((st.recv(data)).decode('utf-8')) print(header_json) file_down = b'' encodeing = None while header_json['total_size'] > 0: msg = st.recv(1024) header_json['total_size'] -= len(msg) file_down += msg try: if encodeing == None: print(msg.decode(encoding='utf-8')) else: print(msg.decode(encodeing='gbk')) except Exception: encodeing == False print(msg.decode(encoding='gbk'))
return file_down
while True:
msg = input('请输入').strip() if not len(msg): continue try: st.send(msg.encode('utf-8')) file_down = get_file(st)
if msg == 'get': with open('save.txt', 'wb') as f: f.write(file_down) print('end')
except ConnectionResetError: break
st.close()
python subprocess 小例子的更多相关文章
- 感受python之美,python简单易懂的小例子
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 1 简洁之美 通过一行代码,体会Python语言简洁之美 2 Python ...
- python闭包小例子
------------------ 首先根据实例, 体会一下闭包的效果 ------------------ 定义闭包: def foo(x): a = [0] def bar(y): a[0] = ...
- python ctypes小例子
import time import ctypes import ctypes.wintypes SEE_MASK_NOCLOSEPROCESS = 0x00000040 SEE_MASK_INVOK ...
- [Python]Python 函数调用小例子
函数定义: In [78]: def printme(str): ....: print str ....: return ....: 调用: In [79]: printme('This is Ji ...
- [Spark][Hive][Python][SQL]Spark 读取Hive表的小例子
[Spark][Hive][Python][SQL]Spark 读取Hive表的小例子$ cat customers.txt 1 Ali us 2 Bsb ca 3 Carls mx $ hive h ...
- [Python]Python 使用 for 循环的小例子
[Python]Python 使用 for 循环的小例子: In [7]: for i in range(5): ...: print "xxxx" ...: print &quo ...
- [python]python 遍历一个list 的小例子:
[python]python 遍历一个list 的小例子: mlist=["aaa","bbb","ccc"]for ss in enume ...
- Python,while循环小例子--猜拳游戏(三局二胜)
Python,while循环小例子--猜拳游戏(三局二胜) import random all_choice = ['石头', '剪刀', '布'] prompt = '''(0)石头 (1)剪刀 ( ...
- 这42个Python小例子,太走心
告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 < ...
随机推荐
- 关于malloc(0)的返回值问题--这两天的总结与实践篇
就像我在http://www.cnblogs.com/wuyuegb2312/p/3219659.html 文章中评论的那样,我也碰到了被提问这个malloc(0)的返回值问题,虽然感觉这样做在实际中 ...
- 30.SSH配置文件模板和类库.md
目录 1.struts2 4.类库 1.struts2 1.<?xml version="1.0" encoding="UTF-8"?>2.< ...
- (转)NHibernate+MySql常见问题
http://blog.51cto.com/4837471/1567675 版本: NHibernate :NHibernate 4.0.1GA MySql:MySql 5.0.1 常见问题一: “N ...
- unity3d热更新插件uLua学习整理
前言 IOS不能热更新,不是因为不能用反射,是因为System.Reflection.Assembly.Load 无法使用System.Reflection.Emit 无法使用System.CodeD ...
- Spark MLlib特征处理:OneHotEncoder OneHot编码 ---原理及实战
http://m.blog.csdn.net/wangpei1949/article/details/53140372 Spark MLlib特征处理:OneHotEncoder OneHot编码 - ...
- 弹窗切换page进行关闭
beforeRouteLeave(to,from,next){ //这里写关闭弹窗 // 这里跳转路由 MessageBox.close(); next() // next()别漏,不然不跳转 }
- js基础-数组及数据类型
数组也是引用类型 构造函数创建数组 Object 构造函数类型(所有类型基类) Array 构造函数类型 求幂运算符 ** 2**32-1 数组容量最大 arry.length 如果减小len ...
- 理解 e.clientX,e.clientY e.pageX e.pageY e.offsetX e.offsetY
event.clientX.event.clientY 鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条.IE事件和标准事件都定义了这2个属性 event.pageX ...
- Tensorflow函数——tf.variable_scope()
Tensorflow函数——tf.variable_scope()详解 https://blog.csdn.net/yuan0061/article/details/80576703 2018年06月 ...
- springboot找不到主类
在学习springboot的时候,前几天写了一个demo,正常运行,一点问题也没有.今天运行不起来了. 报错:找不到主类 解决方案: Project->Clean->选中项目,点击Clea ...