这是用于Windows环境。
编译pytestprocess.py(使用pyinstaller)并将生成的exe放在测试文件夹中。
在同一文件夹中,运行ptest.py。
Testprocess.py开始并且永远不会结束,每3秒将一个数字写入stdout。
ptest.py尝试捕获此输出。
此代码模拟了我要解决的生产问题。类似于生产中发生的情况,在测试过程终止之前,不会将stdout释放到ptest.py。在生产中,此过程永远不会停止,但会将重要内容发布到stdout。
有没有一种方法可以做到这一点?
只要子进程终止,附加的代码就可以正常工作。
## [testprocess.py]:
import time
x = 0
while True:
print(x)
time.sleep(3)
x += 1
## [ptest.py]:
import os
import sys
import subprocess
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
start_dir = get_script_path()
cmd = [start_dir + os.sep + 'testprocess.exe']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', universal_newlines=True)
print('Subprocess started.')
capture = ""
s = proc.stdout.read(1)
print('Read Stdout')
while len(s) > 0:
sys.stdout.write(s)
sys.stdout.flush()
capture += s
s = proc.stdout.read(1)
print(s)
print(capture)
sys.exit()
希望能够在子进程仍在运行时捕获它的标准输出,而不必等到它终止。
答案 0 :(得分:0)
有可能,而且比您想像的要容易。子流程启动后,您可以连续尝试从stdout
中读取内容并在有需要打印的地方进行打印。 您可能需要修改testprocess.py
来刷新自身(将flush = True
添加到print
语句中)。
p = subprocess.Popen(command,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
encoding='utf-8',
universal_newlines=True)
while True:
line = p.stdout.readline()
if line == "" and p.poll() is not None:
break
if line:
print(line.strip(), flush = True)
编辑:如果您的命令看起来像python testprocess.py
,则可以通过将flush = True
作为命令选项传递来跳过向打印语句中添加-u
的操作。 -u
告诉python解释器以unbuffered
模式运行。
但是,我看到您的命令实际上正在调用exe
文件。您可能需要弄清楚如何告诉编译器如何将程序编译为unbuffered
。