Python subprocess.Popen 挂在“for l in p.stdout”中直到 p 终止,为什么?
我有这样的代码:
#!/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”不会退出,它会不断向标准输出输出越来越多的数据。但是,该代码不会给出任何输出,只是在 tun.stdout 中继续等待。
当我在外部终止 newtunnel 进程时,它将所有数据刷新到 tun.stdout。所以看来我无法从 tun.stdout 仍在运行时获取任何数据。
这是为什么?我怎样才能得到这些信息?
请注意,Popen 的默认 bufsize 为 0(无缓冲)。我还可以指定 bufsize=0 但这不会改变任何东西。
I have that code:
#!/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
The "./newtunnel" will not exit, it will constantly output more and more data to stdout. However, that code will not give any output and just keeps waiting in the tun.stdout.
When I kill the newtunnel process externally, it flushes all the data to tun.stdout. So it seems that I can't get any data from the tun.stdout while it is still running.
Why is that? How can I get the information?
Note that the default bufsize for Popen is 0 (unbuffered). I can also specify bufsize=0 but that doesn't change anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,看来这是Python中的一个错误: http://bugs.python.org/issue3907
如果我更换线路
,
那么它就会完全按照我想要的方式工作。
Ok, it seems that it is a bug in Python: http://bugs.python.org/issue3907
If I replace the line
by
then it works exactly the way I want.