Home >Backend Development >Python Tutorial >How to Capture Live Subprocess Output and Log it Simultaneously?
Live Output from Subprocess Command
To capture both live output and store it for logging, employ one of these approaches:
Using an Iterator
Create an iterator to read from the subprocess stdout and simultaneously write to it:
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)
Using a Writer and Reader
Pass a writer to the subprocess and read from a reader:
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())
The above is the detailed content of How to Capture Live Subprocess Output and Log it Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!