我收到一条消息,说脚本xyz.py返回退出代码0。这是什么意思?

Python中的退出码是什么意思?有多少个?哪些是重要的?


当前回答

退出代码0通常表示“这里没有问题”。但是,如果脚本的程序员没有遵循约定,您可能需要参考源代码来了解它的含义。通常非零值作为错误代码返回。

其他回答

操作系统命令有退出码。请查看Linux退出代码以了解有关这方面的一些材料。shell使用退出代码来决定程序是否工作、是否存在问题或是否失败。有一些努力来创建标准的(或者至少是常用的)退出码。请参阅这篇高级Shell脚本文章。

来自sys.exit的文档:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.

一个使用退出码的例子是在shell脚本中。在Bash中,您可以检查特殊变量$?对于最后一个退出状态:

me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43

就我个人而言,我尝试使用在/usr/include/asm-generic/errno.h(在Linux系统上)中找到的退出码,但我不知道这样做是否正确。

我建议使用内置的exit(0)干净地关闭,而不是使用sys.exit()

我不确定这是不是一个好建议。

所提到的文件如下:

site模块(在启动过程中自动导入,除非给出了-S命令行选项)将几个常量添加到内置名称空间。它们对于交互式解释器shell很有用,不应该在程序中使用。

然后:

退出(代码=没有) 对象,在打印时,打印类似“使用quit()或Ctrl-D(即EOF)退出”的消息,并在调用时引发带有指定退出码的SystemExit。

如果我们将它与sys.exit()文档进行比较,它使用的机制与引发SystemExit异常的机制相同。

如果您希望可移植地使用标准POSIX退出码,请参阅PyPI上的exitstatus包。

安装包:

$ pip install exitstatus

在你的代码中使用:

import sys
from exitstatus import ExitStatus

sys.exit(ExitStatus.success)

有一个errno模块定义了标准退出码:

例如,“Permission denied”是错误码13:

import errno, sys

if can_access_resource():
    do_something()
else:
    sys.exit(errno.EACCES)