Home > Backend Development > Python Tutorial > How do I redirect the output of an external command to a file using the `subprocess` module in Python?

How do I redirect the output of an external command to a file using the `subprocess` module in Python?

DDD
Release: 2024-11-29 00:50:10
Original
765 people have browsed it

How do I redirect the output of an external command to a file using the `subprocess` module in Python?

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
Copy after login

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
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template