8

I wrote this simple code:

#!/usr/bin/python2.7 -tt import subprocess def main() try: process = subprocess.check_output(['unvalidcommand'],shell=True) except CalledProcessError: print 'there is the calledProcessError' if __name__ == '__main__': main() 

Expected output: there is the calledProcessError

What I got: NameError: global name 'CalledProcessError' is not defined

1
  • 6
    Should be subprocess.CalledProcessError. Commented Jul 31, 2014 at 12:28

2 Answers 2

12
def main(): try: process = subprocess.check_output(['unvalidcommand'],shell=True) except subprocess.CalledProcessError: # need to use subprocess.CalledProcessError print 'there is the calledProcessError' main() there is the calledProcessError /bin/sh: 1: unvalidcommand: not found 

Or just import what you need from subprocess:

from subprocess import check_output,CalledProcessError def main(): try: process = check_output(['unvalidcommand'],shell=True) except CalledProcessError: print 'there is the calledProcessError' main() 
Sign up to request clarification or add additional context in comments.

Comments

5

subprocess.CalledProcessError is not a builtin exception. You need to qualify the exception name to use it.

except subprocess.CalledProcessError: ^^^^^^^^^^^ 

or you need to import it explicitly:

from subprocess import CalledProcessError 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.