[lug] Python: Unable to catch subprocess error

Jed S. Baer blug at jbaer.cotse.net
Fri Mar 9 20:12:38 MST 2018


On Fri, 9 Mar 2018 19:39:55 -0700
Rob Nagler wrote:

> 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".

Well, I suppose in context, the docs are trying to relate to the value
"returned" by the method in its return object. But still, it would seem
that the subprocess exit status is returned as a "code" as in "error
code". Poor wording choice. But then I wonder whether the writer is in
fact being very precise, and choosing that instead of exit status, and
what that would mean.

> 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.

My understanding is that "except", by itself, is a catch-all. This would
seem to be good practice in an error handler. It catches anything not
explicitly handled.

> "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:

Oh, that's just my being lazy, as taught by languages that do automatic
casting. In my Pythonic endeavours to this point, haven't had to think
about it. But thanks for the push to read up on Python string formatting.


More information about the LUG mailing list