如果我使用例如“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