<分区>
我有两个脚本。 (代码在下面列出)。第一个脚本只是延迟打印数字。
第二个脚本应该作为子进程启动第一个脚本,然后在后台检查(!)如果第一个脚本输出数字,如果是则打印它。
但我得到的是第二个脚本在第一个脚本终止时(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)
测试.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')