简体   繁体   中英

How to capture the output from “subprocess.call” to a file?

In my code I have a line similar to this:

rval = subprocess.call(["mkdir",directoryName], shell=True)

and I can check rval to see if it is 0 or 1 , but if it is 1 , I would like to have the text from the command "A subdirectory or file ben already exists." in a file format, so I can compare it to another file if I want to make sure the text is the same.

Is it possible to have a line like this, but I know this does not work

rval = subprocess.call(["mkdir",directoryName], shell=True) >> filename

so no matter what happens with the command, the text is captured in filename , and rval still has the return code?

The subprocess module has a built in 'check_output' function for doing this:

In [11]: result = subprocess.check_output(['pwd'])

In [12]: print result
/home/vagrant
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
import subprocess

try:
    result = subprocess.check_output(['dir', r'c:\temp'], shell=True)
    print result
except subprocess.CalledProcessError as e:
    return_code = e.returncode

You anyway need to use try catch because it throws exception if return code is non zero :)

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