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?
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.
pytest command line usage error. Exit code 5. No tests were collected.
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.
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 “.
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 Csystem()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With