简体   繁体   中英

how to capture error from python's subprocess.run, while using timeout

I cannot figure out how to use python's subprocess.run to capture stdout, stderr, and exitcode ... and whatever else can be captured. I also have to use the timeout option because some of the thousands of commands I'm running hang, ie., run interminably. I bet I have missed something obvious, and I apologize. I've spent days on this and cannot figure it out.

Any help you could give me would be much appreciated.

Here's my defective code:

seconds = timeout
try:
    proc = subprocess.run(cmd, capture_output=True, timeout=seconds)

except subprocess.TimeoutExpired:
    print('This process ran too long:\n' + cmd + '\n')
        
out, err = proc.communicate()
exitcode = proc.returncode

if len(out) == 0: out="''"
if len(err) == 0: err="''"
#
return exitcode, out, err

You're almost there. Instead of

out, err = proc.communicate()

use

out, err = proc.stdout, proc.stderr

Regarding your except clause, I'm not sure if you'll be able to get stdout, stderr and returncode after a timeout. Give it a check. If not, then consider return "", "", 1 or something like that in your except clause.

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