我收到一条消息,说脚本xyz.py返回退出代码0。这是什么意思?
Python中的退出码是什么意思?有多少个?哪些是重要的?
我收到一条消息,说脚本xyz.py返回退出代码0。这是什么意思?
Python中的退出码是什么意思?有多少个?哪些是重要的?
当前回答
来自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系统上)中找到的退出码,但我不知道这样做是否正确。
其他回答
在许多编程语言中,退出码由程序员决定。因此您必须查看您的程序源代码(或手册)。零通常表示“一切都很好”。
处理: 为了解决gitlab-ci (https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27668)中的错误,我简单地生成了一个包含错误代码的文件:
Python的部分:
with open("error_code.log", 'w') as file:
file.write('2') # this will trigger a warning
然后在yml文件中:
.step_name:
variables:
# my vars
script:
- python my_code.py arg1 arg2
- exit `cat error_code.log`
allow_failure:
exit_codes:
- 2
下面是Unix退出代码0 -成功/ OK, 1 -不成功/错误。你可以简单地使用exit(0)或exit(1)调用而不导入sys module。
为了允许异常处理程序和其他事情执行,我建议使用内置的exit(0)干净地关闭,而不是使用sys.exit()突然终止进程。
退出码只有脚本作者指定的意义。Unix的传统是,退出码0表示“成功”,否则就是失败。要确定给定脚本的退出码意味着什么,唯一的方法是检查脚本本身。