Reputation: 163
Here is my code:
from subprocess import check_output
print check_output('whoami', shell=True)
This works fine.
However, if I put a command that isnt' existent it will say:
raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'test' returned non-zero exit status 1
When if you were to run this on your shell, it would say something like:
'test' isnot recognized as an intenral or external command, operable program or batch file.
How can I get this instead?
Upvotes: 1
Views: 439
Reputation: 31524
As you can read in the subprocess.check_output
documentation:
If the return code was non-zero it raises a
CalledProcessError
. TheCalledProcessError
object will have the return code in the returncode attribute and any output in the output attribute.
So you can do this:
import subprocess
try:
print subprocess.check_output('test', shell=True)
except subprocess.CalledProcessError, e:
print e.output
Upvotes: 2