0

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.

Evan
  • 1,960
  • 4
  • 26
  • 54
  • This is something you'd do in the environment where you run the script (e.g. in bash), not from within the script itself. – arshajii Feb 29 '16 at 21:46

2 Answers2

3

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Is there a way to find the exit code in python, like if the exit code is 0 or 1 or n, assign that value to a variable? – Evan Feb 29 '16 at 21:51
  • That explanation makes sense; it would have to look back in on itself while running. – Evan Feb 29 '16 at 21:57
  • 1
    Unfortunately, [`sys.excepthook()`](https://docs.python.org/2/library/sys.html#sys.excepthook) is not called for `SystemExit` exceptions. Otherwise I'd have totally posted an answer with that. :-P (And no, using `atexit` and checking for `sys.exc_info()` is also pointless). – Martijn Pieters Feb 29 '16 at 21:59
  • This answer could just tack on an `except Exception: print('Error'); raise` I suppose. . . – mgilson Feb 29 '16 at 22:18
1

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.

Community
  • 1
  • 1
Peter Badida
  • 11,310
  • 10
  • 44
  • 90
  • That makes sense. I was using this method, I just wasn't sure if it was fool-proof. – Evan Feb 29 '16 at 21:59