Clean way to return error codes

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Nov 21 02:09:51 EST 2016


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?




-- 
Steven
299792.458 km/s — not just a good idea, it’s the law!




More information about the Python-list mailing list