Redirecting Output with Subprocess in Python
In Python, the subprocess module allows for the invocation of external commands. When executing commands, it's often desirable to redirect the output to a file.
Consider the following command line command:
cat file1 file2 file3 > myfile
This command concatenates files file1, file2, and file3 and redirects the output to the myfile file. To achieve similar functionality in Python, you can initially attempt the following:
import subprocess, shlex my_cmd = 'cat file1 file2 file3 > myfile' args = shlex.split(my_cmd) subprocess.call(args) # Spits output in the window from which Python was called
However, this approach doesn't redirect the output to a file. Instead, it prints it to the window where the Python program was invoked.
Python 3.5 Solution
To properly redirect the output, provide an open file handle for the stdout argument in subprocess.run:
input_files = ['file1', 'file2', 'file3'] my_cmd = ['cat'] + input_files with open('myfile', "w") as outfile: subprocess.run(my_cmd, stdout=outfile)
This solution effectively redirects the output to the myfile file without the need for an external command like cat.
The above is the detailed content of How do I redirect the output of an external command to a file using the `subprocess` module in Python?. For more information, please follow other related articles on the PHP Chinese website!