Clean way to return error codes

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Nov 21 02:39:35 EST 2016


Steven D'Aprano writes:

> I have a script that can be broken up into four subtasks. If any of
> those subtasks fail, I wish to exit with a different exit code and
> error.
>
> Assume that the script is going to be run by system administrators who
> know no Python and are terrified of tracebacks, and that I'm logging
> the full traceback elsewhere (not shown).
>
> I have something like this:
>
>
> try:
>     begin()
> except BeginError:
>     print("error in begin")
>     sys.exit(3)
>
> try:
>     cur = get_cur()
> except FooError:
>     print("failed to get cur")
>     sys.exit(17)
>
> try:
>     result = process(cur)
>     print(result)
> except FooError, BarError:
>     print("error in processing")
>     sys.exit(12)
>
> try:
>     cleanup()
> except BazError:
>     print("cleanup failed")
>     sys.exit(8)
>
>
>
> It's not awful, but I don't really like the look of all those
> try...except blocks. Is there something cleaner I can do, or do I just
> have to suck it up?

Have the exception objects carry the message and the exit code?

try:
    begin()
    cur = get_cur()
    result = process(cur)
    print(result)
    cleanup()
except (BeginError, FooError, BarError, BazError) as exn:
    print("Steven's script:", message(exn))
    sys.exit(code(exn))



More information about the Python-list mailing list