Reputation: 1127
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?
Upvotes: 6
Views: 7142
Reputation: 1121894
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.
Upvotes: 10