我一直在使用诸如
subprocess.Popen(f"py test.py hello &", shell=True, universal_newlines=True)
这将打开脚本 test.py:
import time
import sys
while True:
print(sys.argv[1])
time.sleep(1)
但是,如果我运行多次等
subprocess.Popen(f"py test.py hello &", shell=True, universal_newlines=True)
subprocess.Popen(f"py test.py world &", shell=True, universal_newlines=True)
subprocess.Popen(f"py test.py stackoverflow &", shell=True, universal_newlines=True)
这意味着这些运行中的每一个都有自己的 sys.argv[1] 值,并且会一遍又一遍地打印出来。
但是我的问题是,我想创建一个脚本,我在其中调用 etcpy outprints.py test hello
"所有带有"hello"参数的 test.py都应该打印并在此过程中继续打印subprocess.Popen(f"py test.py hello &", shell=True, universal_newlines=True)
我想知道是否有可能做这样一个脚本来读取后台运行的脚本的输出日志并查看其输出,如果是,我能做什么?
下面是将其中一个子流程的输出读回主进程的示例。
import subprocess
proc = subprocess.Popen(["python", "test.py", "hello"],
stdout=subprocess.PIPE)
# read 5 lines of output from the subprocess and then kill it
for i in range(5):
line = proc.stdout.readline()
print("The subprocess said ", line.decode())
proc.kill()
在test.py
中,您应该插入一条语句来刷新输出:
import time
import sys
while True:
print(sys.argv[1])
sys.stdout.flush()
time.sleep(1)
这将确保输出数据可立即读取。 否则,您将等待很长时间,直到看到任何输出,因为它将保存在缓冲区中。