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
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.
catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”.
The only exception that cannot be caught directly is (a framework thrown) StackOverflowException. This makes sense, logically, as you don't have the space in the stack to handle the exception at that point.
Instead of getting sick of try/catch, there is another way of checking if the executable throws an error, using custom error instances.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With