子進程命令的即時輸出
要擷取即時輸出並將其儲存以進行記錄,請採用以下方法之一:
使用迭代器
建立迭代器從子進程標準輸出讀取並同時寫入:
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中文網其他相關文章!