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

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


当前回答

处理: 为了解决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表示“成功”,否则就是失败。要确定给定脚本的退出码意味着什么,唯一的方法是检查脚本本身。

处理: 为了解决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

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

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

import errno, sys

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

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

安装包:

$ pip install exitstatus

在你的代码中使用:

import sys
from exitstatus import ExitStatus

sys.exit(ExitStatus.success)

下面是Unix退出代码0 -成功/ OK, 1 -不成功/错误。你可以简单地使用exit(0)或exit(1)调用而不导入sys module。