Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.exit return code

Tags:

python

I try to call another python script in a python script, and get the return code as follows:

print os.system("python -c 'import sys; sys.exit(0)'")
print os.system("python -c 'import sys; sys.exit(1)'")

I get return code 0 and 256. Why it returns 256, when I do sys.exit with value 1?

like image 242
GarudaReiga Avatar asked May 21 '14 16:05

GarudaReiga


People also ask

How do you exit a return code in Python?

exit(1) (or any non-zero integer), the shell returns 'Not OK'. It's your job to get clever with the shell, and read the documentation (or the source) for your script to see what the exit codes mean. Just for completeness, 'Not OK' will be printed if Python script raised error OR had syntax error.

What is exit code 5 in Python?

pytest command line usage error. Exit code 5. No tests were collected.

What does Sys exit 0 do in Python?

The function calls exit(0) and exit(1) are used to reveal the status of the termination of a Python program. The call exit(0) indicates successful execution of a program whereas exit(1) indicates some issue/error occurred while executing a program.

What does exit () do in Python?

exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers. After writing the above code (python os. exit() function), the output will appear as a “ 0 1 2 “.


1 Answers

Quoting the os.system() documentation

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

Emphasis mine. The return value is system dependent, and returns an encoded format.

The os.wait() documentation says:

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

This is not the exit status you are looking at, but an exit status indication, which is based of the return value of the C system() call, whose return value is system-dependent.

Here, your exit status of 1 is packed into the high byte of a 16-bit value:

>>> 1 << 8
256

You could extract the exit code and signal with:

exit_code, signal, core = status_ind >> 8, status_ind & 0x7f, bool(status_ind & 0x80)

but keep the system-dependent caveat in mind.

Use the subprocess module if you want to retrieve the exit code more reliably and easily.

like image 188
Martijn Pieters Avatar answered Oct 13 '22 00:10

Martijn Pieters