Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect output with subprocess in Python?

What I do in the command line:

cat file1 file2 file3 > myfile 

What I want to do with python:

import subprocess, shlex my_cmd = 'cat file1 file2 file3 > myfile' args = shlex.split(my_cmd) subprocess.call(args) # spits the output in the window i call my python program 
like image 892
catatemypythoncode Avatar asked Feb 11 '11 02:02

catatemypythoncode


People also ask

How do I get output to run from subprocess?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

How do you call a subprocess in Python?

To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.

What is subprocess popen ()?

The subprocess. popen() is one of the most useful methods which is used to create a process. This process can be used to run a command or execute binary. The process creation is also called as spawning a new process which is different from the current process.


1 Answers

In Python 3.5+ to redirect the output, just pass an open file handle for the stdout argument to subprocess.run:

# Use a list of args instead of a string input_files = ['file1', 'file2', 'file3'] my_cmd = ['cat'] + input_files with open('myfile', "w") as outfile:     subprocess.run(my_cmd, stdout=outfile) 

As others have pointed out, the use of an external command like cat for this purpose is completely extraneous.

like image 184
Ryan C. Thompson Avatar answered Oct 02 '22 16:10

Ryan C. Thompson