Executing Executables with Output to Both Files and Terminal
When executing multiple executables using subprocess.call(), you may want to direct the standard output and error output to both files and the terminal. However, using stdout=outf or stderr=errf only specifies that the output should be written to a file, not displayed on the terminal.
To achieve the desired behavior, you can leverage the Popen class directly and use the stdout=PIPE argument to capture the standard output in a pipe instead of a file. Here's how you can do that:
<code class="python">from subprocess import Popen, PIPE with open("out.txt", "wb") as outf, open("err.txt", "wb") as errf: p = Popen(["cat", __file__], stdout=PIPE, stderr=errf) # Read the output from the pipe output = p.stdout.read() # Write the output to the terminal print(output) # Ensure the process completes and wait for the output to be fully written p.wait()</code>
In this example, we capture the stdout in a pipe and read it using p.stdout.read(). We then print the output to the terminal before waiting for the process to complete and for the output to be fully written to the files. This ensures that the output is displayed on the terminal as well as written to the specified files.
The above is the detailed content of How to Redirect Executable Output to Both Files and the Terminal?. For more information, please follow other related articles on the PHP Chinese website!