使用 subprocess.Popen 时如何获取打印件
How to get prints when using subprocess.Popen
我一直在使用诸如
之类的脚本
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 Whosebug &", shell=True, universal_newlines=True)
这意味着这些 运行 中的每一个都有自己的 sys.argv[1] 值,并且会一遍又一遍地打印出来。
但是我的问题是,我想创建一个脚本,我调用 etc py outprints.py test hello
"All test.py with the argv of "hello" 应该打印并继续打印过程
共 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)
这将确保输出数据可立即读取。否则你将等待很长时间才能看到任何输出,因为它会保存在缓冲区中。
我一直在使用诸如
之类的脚本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 Whosebug &", shell=True, universal_newlines=True)
这意味着这些 运行 中的每一个都有自己的 sys.argv[1] 值,并且会一遍又一遍地打印出来。
但是我的问题是,我想创建一个脚本,我调用 etc py outprints.py test hello
"All test.py with the argv of "hello" 应该打印并继续打印过程
共 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)
这将确保输出数据可立即读取。否则你将等待很长时间才能看到任何输出,因为它会保存在缓冲区中。