Home  >  Article  >  Backend Development  >  How Can I Write Subprocess Output to Both the Terminal and Files Simultaneously in Python?

How Can I Write Subprocess Output to Both the Terminal and Files Simultaneously in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 22:58:30740browse

How Can I Write Subprocess Output to Both the Terminal and Files Simultaneously in Python?

Writing Process Output to Terminal and Files Simultaneously with Python's subprocess

When executing multiple executables using subprocess.call(), it's desirable to have output displayed in both the terminal and a designated file. However, the default behavior only allows output redirection to either file or terminal.

To overcome this limitation, consider using Popen directly in conjunction with the stdout=PIPE argument. This will enable you to read output from the stdout attribute of the Popen object.

To achieve the desired behavior, employ the following steps:

  • Create a tee() function: This function spawns a thread to forward input from one file to multiple output files.
  • Implement a teed_call() function: This function emulates subprocess.call() but accepts additional stdout and stderr file arguments. It uses tee() to write output to both files and the terminal.

Here's an example of how to use these functions:

<code class="python">import sys
from subprocess import Popen, PIPE
from threading import Thread

def tee(infile, *files):
    ...

def teed_call(cmd_args, **kwargs):
    ...

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)</code>

This code effectively writes output to both the files and the terminal concurrently for each executed command.

The above is the detailed content of How Can I Write Subprocess Output to Both the Terminal and Files 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