简体   繁体   中英

How do I redirect stdout to a file when using subprocess.call in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM