1

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.

ankit
  • 1,499
  • 5
  • 29
  • 46

1 Answers1

5

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?

Community
  • 1
  • 1
SethMMorton
  • 45,752
  • 12
  • 65
  • 86
  • 1
    Actually it prints 0 or 255! Exit code in Unix systems is a 16 bit wide value and the returned exit code is the upper 8 bits of it (lower 8 bit states if core dump has been created and the signal number, if any). `python -c 'exit(-1)'; echo $?` prints 255. – TrueY Feb 10 '22 at 14:41