1

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?

2
  • It's much more robust to use check_call which gives you a clear indication of a failure instead of having to look at the text. As to your question -- if you want the shell, use the shell. Commented Aug 14, 2014 at 14:40
  • You can use proc = subprocess.Popen('test', shell=True) Commented Aug 14, 2014 at 14:53

1 Answer 1

2

As you can read in the subprocess.check_output documentation:

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.