Search code examples
pythonexit-code

Get Exit Status of a Nested Function?


I have a function called within a different function. In the nested function, various errors (e.g. improper arguments, missing parameters, etc.) should result in exit status 1. Something like:

if not os.path.isdir(filepath):
    print('Error: could not find source directory...')
    sys.exit(1)

Is this the correct way to use exit statuses within python? Should I have, instead,

return sys.exit(1)

??? Importantly, how would I reference the exit status of this nested function in the other function once the nested function had finished?


Solution

  • sys.exit() raises a SystemExit exception. Normally, you should not use it unless you really mean to exit your program.

    You could catch this exception:

    try:
        function_that_uses_sys.exit()
    except SystemExit as exc:
        print exc.code
    

    The .code attribute of the SystemExit exception is set to the proposed exit code.

    However, you should really use a more specific exception, or create a custom exception for the job. A ValueError might be appropriate here, for example:

    if not os.path.isdir(filepath):
        raise ValueError('Error: could not find source directory {!r}'.format(filepath))
    

    then catch that exception:

    try:
        function_that_may_raise_valueerror()
    except ValueError as exc:
        print "Oops, something went wrong: {}".format(exc.message)