博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
subprocess 进程使用
阅读量:7037 次
发布时间:2019-06-28

本文共 1385 字,大约阅读时间需要 4 分钟。

同步进程

import subprocess cmd = ('tail', '/tmp/test.log') sp = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE) if sp.wait() == 0: print 'exec command succussful.' else: print sp.stderr.read()
 

异步进程

import subprocess cmd = ('tail', '-f', '/tmp/test.log') sp = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE) while True: if sp.poll() is not None: print 'exec command completed.' else: print sp.stdout.readline()
 

进程通讯

sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdoutput,erroutput) = sp.communicate()

sp.communicate会一直等到进程退出,并将标准输出和标准错误输出返回,这样就可以得到子进程的输出了,上面,标准输出和标准错误输出是分开的,也可以合并起来,只需要将stderr参数设置为subprocess.STDOUT就可以了,这样子:

sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdoutput,erroutput) = sp.communicate()

如果你想一行行处理子进程的输出,也没有问题:

sp=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True:     buff = sp.stdout.readline() if buff == '' and sp.poll() != None: break else: print buff

死锁如果你使用了管道,而又不去处理管道的输出,那么小心点,如果子进程输出数据过多,死锁就会发生了,比如下面的用法:

sp=subprocess.Popen("longprint", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sp.wait()

longprint是一个假想的有大量输出的进程,那么在我的xp, Python2.5的环境下,当输出达到4096时,死锁就发生了。当然,如果我们用sp.stdout.readline或者sp.communicate 去清理输出,那么无论输出多少,死锁都是不会发生的。或者我们不使用管道,比如不做重定向,或者重定向到文件,也都是可以避免死锁的。

 

转载地址:http://btnal.baihongyu.com/

你可能感兴趣的文章
Zabbix之自动发现
查看>>
DOS功能调用——单个字符及字符串的输入输出
查看>>
UITextField基础属性
查看>>
Java实现生产者和消费者的三种方法
查看>>
好程序员大数据培训之ZooKeeper应用-解决分布式系统单点故障
查看>>
有种速度让你望尘莫及 | 手机QQ及Qzone速度优化实践
查看>>
Cocos2d-x3.2 Grid3D网格动作
查看>>
VS2012使用技巧
查看>>
学习笔记-小甲鱼Python3学习第六讲:python之常用操作符
查看>>
高性能服务器——I/O多路转接的三种模式(select &poll& epoll)
查看>>
centos6.5编译redis3.0.3
查看>>
Docker 之 LNMPA(Nginx + PHP + Apache + MySQL) 环境
查看>>
安装httpd2.4
查看>>
JPA(五)之实体关系多对多
查看>>
Zookeeper学习笔记-zookeeper介绍
查看>>
mysql学习笔记(4-通用二进制格式安装MariaDB)
查看>>
【Django入门与实践】课程系列第2篇
查看>>
Android APK 瘦身实践
查看>>
仿车轮社区图片切换效果
查看>>
执行计划的操作类型
查看>>