Search code examples
python-2.7windows-shell

Checking exit code returned by a python function


I have written a python function

def foo():
    if A:
        do something
    if B:
        exit(-1)

if __name__ == "__main__":
    foo()

Is there any way to check the exit code returned by foo function? I am running it from windows shell.


Solution

  • To check the exit code, you look at the variable $? (in sh/bash/csh/etc.). Let's say your script is in a file foo.py.

    $ ./foo.py
    $ echo $?  # Prints 0 on success, -1 on failure.
    

    This is not specific to python, BTW. It is true for all programs that return an exit code.


    The exit code is not from the foo function, but rather from the sys.exit() function. If the program exits due to an exception, it has exit code 1. If you pass a number to sys.exit(), it exits with that exit code. Otherwise, it has exit code 0.


    For Windows shell check out this answer: How do I get the application exit code from a Windows command line?