Redirecting Output with subprocess in Python
In this snippet, we aim to execute a command that combines the contents of multiple files into a single file using Python's subprocess module. Our goal is to redirect the output of the command to a file without displaying it in the console.
In Python 3.5 , you can achieve this redirection by passing an open file handle to the stdout argument of subprocess.run:
input_files = ['file1', 'file2', 'file3'] my_cmd = ['cat'] + input_files with open('myfile', "w") as outfile: subprocess.run(my_cmd, stdout=outfile)
The with block ensures that the 'myfile' file is properly closed after the operation. The subprocess.run function executes the command and redirects the output to the specified file.
Note that the use of an external command like cat is unnecessary for this task. You could simply read the files and concatenate their contents within your Python program.
The above is the detailed content of How to Redirect Command Output to a File with subprocess.run in Python?. For more information, please follow other related articles on the PHP Chinese website!