Home >Backend Development >Python Tutorial >How can I redirect subprocess output to a file in Python?
Redirecting Output in Python with Subprocess
In Python, redirecting output to a file using subprocess can be accomplished through the stdout argument when invoking subprocess.run().
Consider the following command line command:
cat file1 file2 file3 > myfile
This command concatenates the contents of files "file1", "file2", and "file3" and directs the output to the file "myfile".
To perform an analogous operation in Python using subprocess, follow these steps:
Example Code (Python 3.5 ):
import subprocess # Create a list of input file names input_files = ['file1', 'file2', 'file3'] # Create the command argument list my_cmd = ['cat'] + input_files # Open the output file in write mode with open('myfile', "w") as outfile: # Run the subprocess and redirect its output to the file subprocess.run(my_cmd, stdout=outfile)
By following this approach, you can effectively redirect the output of a subprocess to a specified file.
The above is the detailed content of How can I redirect subprocess output to a file in Python?. For more information, please follow other related articles on the PHP Chinese website!