Search code examples
pythonsubprocesspsexec

subprocess.check_ouput() return code


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!


Solution

  • 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