gpt4 book ai didi

Python sys.exit 返回代码

转载 作者:太空狗 更新时间:2023-10-30 02:04:08 25 4
gpt4 key购买 nike

我尝试在一个python脚本中调用另一个python脚本,得到返回码如下:

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

我得到返回代码 0 和 256。为什么当我使用值 1 执行 sys.exit 时返回 256?

最佳答案

引用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.

强调我的。返回值取决于系统,并返回一个编码格式。

os.wait() documentation说:

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.

不是您正在查看的退出状态,而是一个退出状态指示,它基于 C system() 的返回值 调用,其返回值是系统相关的。

这里,你的1的退出状态被打包到一个16位值的高字节中:

>>> 1 << 8
256

您可以使用以下方式提取退出代码和信号:

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

但请牢记系统相关警告。

使用 subprocess module如果您想更可靠、更轻松地检索退出代码。

关于Python sys.exit 返回代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com