Python subprocess.Popen在'p.stdout'中挂起,直到进程终止,为什么?
我有这样的代码:
#!/usr/bin/python -u
localport = 9876
import sys, re, os
from subprocess import *
tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT)
print "** Started tunnel, waiting to be ready ..."
for l in tun.stdout:
sys.stdout.write(l)
if re.search("Waiting for connection", l):
print "** Ready for SSH !"
break
这个"./newtunnel"不会退出,它会不断地往标准输出(stdout)里输出更多的数据。不过,这段代码不会有任何输出,只是一直在等待tun.stdout。
当我在外部结束newtunnel进程时,它会把所有的数据都刷新到tun.stdout。所以看起来在newtunnel还在运行的时候,我无法从tun.stdout获取任何数据。
这是为什么呢?我该如何获取这些信息呢?
需要注意的是,Popen的默认缓冲区大小是0(无缓冲)。我也可以指定bufsize=0,但这并没有改变什么。
1 个回答
2
好的,看起来这是Python中的一个错误:http://bugs.python.org/issue3907
如果我把这一行
for l in tun.stdout:
换成
while True:
l = tun.stdout.readline()
那么它就能完全按照我想要的方式工作了。