[lug] Python: Unable to catch subprocess error

Jed S. Baer blug at jbaer.cotse.net
Fri Mar 9 18:58:18 MST 2018


Hi Folks. Any Python experts around?

This seems so trivial; I must be missing something really obvious, or
something explained in a non-obvious section of the docs.

https://docs.python.org/2/library/subprocess.html says:
"Run command with arguments and return its output as a byte string.

If the return code was non-zero it raises a CalledProcessError."

So, I've isolated the code to this:
++++++++++++++++++++
#!/usr/bin/env python

import subprocess

rcmd = ["date"]
try:
    msg_out = subprocess.check_output(rcmd)
except subprocess.CalledProcessError as e:
    msg_out = e.returncode + e.output
    print "\nHey we got here\n"
except:
    raise

print msg_out
++++++++++++++++++++

Change "date" to something that isn't a valid command, or add a bad
option, as in rcmd = ["date", "--geezer"]
and it doesn't print "Hey we got here", and instead does the raise.

So, as far as I can tell, then, maybe all CalledProcessError does is
handle errors involved with the forking of a sub-process, but not the
program that sub-process invoked. But the end of the error stack
(replacing "date" with "bleargh") is:

++++++++++++++++++++
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
++++++++++++++++++++

Which is of course what I'd expect for program not on path. So, are the
docs mis-stating what happens when using that method?

I know I can trap the OSError. But I'm trying to understand the language.

Thanks for any advice.


More information about the LUG mailing list