Home >Backend Development >Python Tutorial >How to Capture Live Subprocess Output and Log it Simultaneously?

How to Capture Live Subprocess Output and Log it Simultaneously?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 10:48:15963browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn