Python使用subprocess.Popen导致子进程hang住

2014-11-24 08:24:46 · 作者: · 浏览: 2

subprocess用于在python内部创建一个子进程,比如调用shell脚本等。


举例:


p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
p.wait()
// hang here
print "subprocess finished"


在python的官方文档中对这个进行了解释:http://docs.python.org/2/library/subprocess.html


原因是stdout产生的内容太多,超过了系统的buffer


解决方法是使用communicate()方法。


p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
stdout, stderr = p.communicate()
p.wait()
print "subprocess finished"