【发布时间】:2016-04-01 04:23:53
【问题描述】:
如果我使用例如“ls -Rlah /”运行以下函数“run”,我会立即通过 print 语句按预期获得输出
import subprocess32 as subprocess
def run(command):
process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
try:
while process.poll() == None:
print process.stdout.readline()
finally:
# Handle the scenario if the parent
# process has terminated before this subprocess
if process.poll():
process.kill()
但是,如果我使用下面的 python 示例程序,它似乎会卡在 process.poll() 或 process.stdout.readline() 上,直到程序完成。我认为它是 stdout.readline() 因为如果我将要输出的字符串数量从 10 增加到 10000(在示例程序中)或在每次打印后添加 sys.stdout.flush() ,运行中的打印函数确实被执行了。
如何使子流程的输出更加实时?
注意:我刚刚发现 python 示例程序在输出时不执行 sys.stdout.flush(),有没有办法让子进程的调用者以某种方式强制执行?
每 5 秒输出 10 个字符串的示例程序。
#!/bin/env python
import time
if __name__ == "__main__":
i = 0
start = time.time()
while True:
if time.time() - start >= 5:
for _ in range(10):
print "hello world" + str(i)
start = time.time()
i += 1
if i >= 3:
break
【问题讨论】:
-
即使使用它,我仍然得到相同的结果。注意我在 python 2.7.10 中使用 subprocess32
-
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 使用以下调用从进程中读取:while process.poll() == None: 打印进程.stdout.readline() 就像上面的例子一样。
-
ahhh :) 而不是执行 print process.stdout.readline() 我为 iter(process.stdout.readline, b"") 中的行执行了但 readline 直到缓冲区才返回脸红了。
-
进程倾向于以不同的方式缓冲取决于 stdout 是终端还是管道。您正在使用管道,因此孩子将阻塞缓冲区。尝试使用
pty模块中的伪终端或使用为此类事物构建的pexpect。 -
1.
command应该是 POSIX 上的列表(例如,"ls -Rlah /".split()) 2. 使用is None而不是== None3.print line双换行,使用print line,(注意:逗号)代替,以抑制第二个不必要的换行符 4.if p.poll(): p.kill()是错误的。见links in the comment
标签: python python-2.7 subprocess