Redirecting Output with Subprocess in Python
To redirect output to a file using subprocess, utilize the stdout argument to specify the file handle.
import subprocess # Specify the input files and command input_files = ['file1', 'file2', 'file3'] command = ['cat'] + input_files # Create a file handle for the output file with open('myfile', "w") as outfile: # Redirect output to the file handle subprocess.run(command, stdout=outfile)
In Python 3.5 and later, this approach is preferred over using subprocess.call with the args argument converted from a string using shlex.split. This ensures that the output is properly redirected to the file.
Note that using an external command like cat is unnecessary in this case, as the same functionality can be achieved directly in Python.
The above is the detailed content of How to Redirect Output to a File Using Subprocess in Python?. For more information, please follow other related articles on the PHP Chinese website!