简体   繁体   中英

Python sys.exit return code

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM