子进程命令的实时输出
要捕获实时输出并将其存储以进行记录,请采用以下方法之一:
使用迭代器
创建迭代器从子进程标准输出读取并同时写入:
import subprocess import sys with open("test.log", "wb") as f: process = subprocess.Popen(your_command, stdout=subprocess.PIPE) for c in iter(lambda: process.stdout.read(1), b""): sys.stdout.buffer.write(c) f.buffer.write(c)
使用写入器和读取器
将写入器传递给子进程并从读取器读取:
import io import time import subprocess import sys filename = "test.log" with io.open(filename, "wb") as writer, io.open(filename, "rb", 1) as reader: process = subprocess.Popen(command, stdout=writer) while process.poll() is None: sys.stdout.write(reader.read()) time.sleep(0.5) # Read the remaining sys.stdout.write(reader.read())
以上是如何捕获实时子流程输出并同时记录它?的详细内容。更多信息请关注PHP中文网其他相关文章!