[lug] Python: Unable to catch subprocess error

Davide Del Vento davide.del.vento at gmail.com
Fri Mar 9 19:34:38 MST 2018


With python the easiest is looking at the source. See
/usr/lib/python2.7/subprocess.py
on line 1327 (or previous in the stack trace) and see.

On Fri, Mar 9, 2018 at 6:58 PM, Jed S. Baer <blug at jbaer.cotse.net> wrote:

> 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.
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: irc.hackingsociety.org port=6667 channel=#hackingsociety
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20180309/bd5d12b1/attachment.html>


More information about the LUG mailing list