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:
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!