Evan
Evan

Reputation: 2038

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.

Upvotes: 0

Views: 2896

Answers (2)

mgilson
mgilson

Reputation: 309909

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.

Upvotes: 3

Peter Badida
Peter Badida

Reputation: 12179

Just write print at the end of a script if it's in form of executing straight from top to bottom. If there's an error, python stops the script and your print won't be executed. The different case is when you use try for managing exceptions.

Or make yourself a script for running python script.py with try and your except will give you an exception for example to a file or wherever you'd like it to store/show.

Upvotes: 1

Related Questions