Search code examples
pythonexit-code

Conditional statement for exit code 0 in Python


Is there a way to have Python print a statement when a script finishes successfully?
Example code would be something like:

if 'code variable' == 0:
    print "Script ran successfully"
else:
    print "There was an error"

How could I pass the value of the exit code to a variable (e.g. 'code variable')?
I feel like this would be a nice thing to include in a script for other users.
Thanks.


Solution

  • You can do this from the shell -- e.g. in Bash:

    python python_code.py && echo "script exited successfully" || echo "there was an error."
    

    You can't have a program write something like this for itself because it doesn't know it's exit code until it has exited -- at which time it isn't running any longer to report the error :-).

    There are other things you can do to proxy this behavior from within the process itself:

    try:
        main()
    except SystemExit as ext:
        if ext.code:
            print ("Error")
        else:
            print ("Success")
        raise SystemExit(ext.code)
    else:
        print ("Success")
    

    However, this doesn't help if somebody uses os._exit -- and we're only catching sys.exit here, no other exceptions that could be causing a non-zero exit status.