简体   繁体   中英

How to redirect Python's subprocess.call() output to file?

I call an exe tool from Python:

args = '-i' + inputFile
cl = ['info.exe', args]
subprocess.call(cl)

How would I redirect output from the info.exe to out.txt ?

You can redirect output to file object by specifying it as stdout argument to subprocess.call . Put it in a context manager to write to file safely.

with open('out.txt', 'w') as f:
    subprocess.call(cl, stdout=f)

Or open the file in wb mode and use subprocess.check_output :

with open('out.txt', 'wb') as f:
    f.write(subprocess.check_output(cl))

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