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.
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.
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.
Pass a file as the stdout
parameter to subprocess.call
:
with open('out-file.txt', 'w') as f:
subprocess.call(['program'], stdout=f)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With