Clean way to return error codes
Peter Otten
__peter__ at web.de
Mon Nov 21 04:13:24 EST 2016
Steven D'Aprano wrote:
> 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?
def run():
yield BeginError, "error in begin", 3
begin()
yield FooError, "failed to get cur", 17
cur = get_cur()
yield (FooError, BarError), "error in processing", 12
result = process(cur)
print(result)
yield BazError, "cleanup failed", 8
cleanup()
try:
for Errors, message, exitcode in run():
pass
except Errors:
print(message)
sys.exit(exitcode)
More information about the Python-list
mailing list