Exit Codes in Python

Exit codes in Python

You're looking for calls to sys.exit() in the script. The argument to that method is returned to the environment as the exit code.

It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.

Difference between exit(0) and exit(1) in Python

0 and 1 are the exit codes.

exit(0) means a clean exit without any errors / problems

exit(1) means there was some issue / error / problem and that is why the program is exiting.

This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was. A zero error code means a successful exit.

This is useful for other programs, shell, caller etc. to know what happened with your program and proceed accordingly.

What is Python's default exit code?

sys.exit documents a default exit status of 0, and os._exit's docs specify a UNIX-like OS constant for "normal" exit status, os.EX_OK, but there is no documented guarantee I can find for the exit status in general.

Aside from that, the best I can give you is that in CPython, the python executable (including python.exe/pythonw.exe on Windows) is implemented in python.c by calling Py_Main and returning whatever it returns; per the documented guarantees on Py_Main, the exit status is:

0 if the interpreter exits normally (i.e., without an exception), 1 if the interpreter exits due to an exception, or 2 if the parameter list does not represent a valid Python command line.

Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the process, as long as Py_InspectFlag is not set.

so this implies that simply running off the end of the __main__ module without an active exception should always return 0 for CPython, though alternate interpreters are not technically required to do the same.

This tracks with the implied exit status rules expected of most applications; while nothing explicitly says Python has to follow those rules, it would be extremely unusual for a tool that grew up in the command line UNIX-like world to violate those conventions.



Related Topics



Leave a reply



Submit