ankit
ankit

Reputation: 1529

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.

Upvotes: 1

Views: 9092

Answers (1)

SethMMorton
SethMMorton

Reputation: 48725

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?

Upvotes: 5

Related Questions