0
votes

I am using subprocess.check_output() to execute some commands on remote machines via Sysinternals PSExec. The issue I'm having is that check_output() raises a CalledProcessError if the command gives a non-zero return code.

PSExec gives the PID of the created process as its return code so obviously I am getting an error every time. Is there a way I can override this error and still check the output of the psexec call? Basically I just need to see the output even though its return code is non-zero.

Thanks!

1
You could use subprocess.call assuming you're not piping stdout/stderr. All that does is run the command, block until it's complete, then return the returncode. - user3960432
Thanks, I actually need the output though as a string, not just the return code. I am searching the output for a key word to make sure that it successfully executed. - DJMcCarthy12

1 Answers

5
votes

Per the docs:

If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute.


try:
    output = subprocess.check_output([...], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
    return_code = err.returncode
    output = err.output