Home  >  Article  >  Backend Development  >  How can I redirect both stdout and stderr from a subprocess to files and the terminal simultaneously in Python?

How can I redirect both stdout and stderr from a subprocess to files and the terminal simultaneously in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 04:13:01428browse

How can I redirect both stdout and stderr from a subprocess to files and the terminal simultaneously in Python?

Output Redirection with Subprocess in Python: Files and Terminal Simultaneously

When utilizing Python's subprocess.call function to execute several executables, users may desire that both stdout and stderr are simultaneously written to specified files and the terminal.

To achieve this, instead of using subprocess.call, one can directly employ the Popen function with the stdout=PIPE argument. This allows for reading from p.stdout:

import sys
from subprocess import Popen, PIPE

def tee(infile, *files):
    for line in iter(infile.readline, b""):
        for f in files:
            f.write(line)

def teed_call(cmd_args, stdout=None, stderr=None):
    p = Popen(
        cmd_args,
        stdout=PIPE if stdout is not None else None,
        stderr=PIPE if stderr is not None else None
    )
    if stdout is not None:
        tee(p.stdout, stdout, getattr(sys.stdout, "buffer", sys.stdout))
    if stderr is not None:
        tee(p.stderr, stderr, getattr(sys.stderr, "buffer", sys.stderr))
    for t in threads:
        t.join()
    return p.wait()

With this modified function, users can specify files for stdout and stderr while still printing to the terminal. For instance:

outf, errf = open("out.txt", "wb"), open("err.txt", "wb")
assert not teed_call(["cat", __file__], stdout=None, stderr=errf)
assert not teed_call(["echo", "abc"], stdout=outf, stderr=errf, bufsize=0)
assert teed_call(["gcc", "a b"], close_fds=True, stdout=outf, stderr=errf)

The above is the detailed content of How can I redirect both stdout and stderr from a subprocess to files and the terminal simultaneously in Python?. 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