Python: 如何在每次输出而不是终止时获取子进程的输出?

Python: How to get an output of subrocess everytime it's outputting and not on terminating?

我有两个脚本。 (代码在下面列出)。第一个脚本只是延迟打印数字。

第二个脚本应该作为子进程启动第一个脚本,然后在后台检查 (!) 如果第一个脚本输出数字,如果是则打印它。

但我得到的是第二个脚本在第一个脚本终止时(20 秒后)立即打印所有数字,而不是每次都打印一个数字。 输出如下:

START
0
1
2
3
4
5
6
7
8
9
16:05:51
OVER

但我期望的是这样的:

START
0
16:05:51
1
16:05:53
2
16:05:55
3
16:05:57
4
16:05:59
5
16:06:01
6
16:06:03
7
16:06:05
8
16:06:07
9
16:06:09
OVER

我该如何解决这个问题?

代码:

1.py:

import time
for i in range(10):
    print(i)
    sys.stdout.flush()
    time.sleep(2)

test.py:

from subprocess import Popen, PIPE, STDOUT
from time import strftime
import threading, sys

stream = Popen(['python', '1.py'], stdout=PIPE, stderr=STDOUT)
def a():
        while True:
            try:
                out = stream.communicate()[0].decode("utf-8")
                print(out, strftime("%H:%M:%S"))
                sys.stdout.flush()
            except ValueError:
                print('OVER')
                break
            except:
                raise
t = threading.Thread(target=a,)
t.start()
print('START')

试试打电话

sys.stdout.flush()

每次打印输出后!

您基本上是在写入缓冲区,这些写入不会变成 "flushed" 直到写入进程完成!所以,如果你不想等到 python 解释器(或下面的 OS)决定 "it is time to flush" ......你必须强制执行该步骤 "manually"!

有关更多背景信息,请参阅其他 answer

编辑:正如您所说,这不适用于 stream:可能您必须 other 方法来调用第二个脚本。您可以尝试使用 pexpect 模块。那个存在的目的是 "sole" "interacting" with stdout output!