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

Barbara Streisand
Release: 2024-11-03 22:58:30
Original
739 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!