[lug] Python: Unable to catch subprocess error

Rob Nagler nagler at bivio.biz
Fri Mar 9 19:39:55 MST 2018


On Fri, Mar 9, 2018 at 6:58 PM, Jed S. Baer wrote:

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

Well, afaik, Unix programs don't have "return codes". They have exit
statuses as in Python's sys.exit. I'm guessing that's what they mean by
"return code".

Things like signals and errors returned by exec/fork are not "return codes"
in subprocess's definition of "return code".

Some tips from a Python neophyte:

You probably don't want to say "except", but rather "except Exception".
There are some exceptions that shouldn't be caught, e.g. SystemExit.

"msg_out = e.returncode + e.output" is invalid. You can't "add" an int to a
string. In general, I find using str.format a better solution to this type
of problem, because you can give context:

msg_out = '{}: command failed with returncode={} and
output:\n{}'.format(rcmd, e.returncode, e.output)

You might also let Python convert the exception to a string:

msg_out = '{}: command failed: {}'.format(cmd, e)

This will usually give you some context, like the return code or the errno
(OSError). Not always. :)

Rob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20180309/08e07682/attachment.html>


More information about the LUG mailing list