【问题标题】:Python subprocess.Popen hangs in 'for l in p.stdout' until p terminates, why?Python subprocess.Popen 在“for l in p.stdout”中挂起,直到 p 终止,为什么?
【发布时间】:2010-05-14 22:28:19
【问题描述】:

我有那个代码:

#!/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 的默认缓冲区大小为 0(无缓冲)。我也可以指定 bufsize=0 但这不会改变任何东西。

【问题讨论】:

标签: python subprocess popen


【解决方案1】:

好吧,看来是Python中的一个bug:http://bugs.python.org/issue3907

如果我换行

for l in tun.stdout:

通过

while True:
    l = tun.stdout.readline()

然后它完全按照我想要的方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2015-05-15
    • 2020-01-22
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多