Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect stdout to a file when using subprocess.call in python?

Tags:

python

I'm calling a python script (B) from another python script (A).

Using subprocess.call, how do I redirect the stdout of B to a file that specify?

I'm using python 2.6.1.

like image 865
Frez Avatar asked Feb 19 '12 05:02

Frez


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.

What does Python subprocess call return?

Return Value of the Call() Method from Subprocess in Python The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.


2 Answers

Pass a file as the stdout parameter to subprocess.call:

with open('out-file.txt', 'w') as f:
    subprocess.call(['program'], stdout=f)
like image 194
icktoofay Avatar answered Sep 28 '22 08:09

icktoofay


Alternate approach

import subprocess
p=subprocess.Popen('lsblk -l|tee a.txt',stdout=subprocess.PIPE,shell=True)
(output,err)=p.communicate()
p_status=p.wait()
print output

Above code will write output of command to file a.txt

like image 26
tabssum Avatar answered Sep 28 '22 06:09

tabssum