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.

2
  • Do you mean from the command line? Commented Feb 20, 2015 at 5:23
  • yes, from command line Commented Feb 20, 2015 at 5:25

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.