Python中的退出代码标准

2024-06-26 14:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

Python(特别是Python CLI实用程序)中是否有既定的出口代码标准或保留的出口代码?(例如,/usr/include/sysexits.h用于UNIX平台中的C,或http://tldp.org/LDP/abs/html/exitcodes.html用于Bash脚本)


Tags: 代码org实用程序http标准cliincludeusr
3条回答

如果您在POSIX平台上,您可以通过^{}模块访问sysexit.h中的常量:

>>> import posix
>>> posix.EX_ <tab pressed>
posix.EX_CANTCREAT    posix.EX_NOHOST       posix.EX_OK           posix.EX_SOFTWARE
posix.EX_CONFIG       posix.EX_NOINPUT      posix.EX_OSERR        posix.EX_TEMPFAIL
posix.EX_DATAERR      posix.EX_NOPERM       posix.EX_OSFILE       posix.EX_UNAVAILABLE
posix.EX_IOERR        posix.EX_NOUSER       posix.EX_PROTOCOL     posix.EX_USAGE

编辑:这些常量可通过^{}模块在所有平台上使用。在

^{}模块提供了几个可以使用的退出代码常量。在

sys.exit(os.EX_OK)
sys.exit(os.EX_USAGE)

关于便携性

虽然退出代码可能有用,但它们可能会带来可移植性问题。文件警告:

Note: Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.

因此,如果您想使用退出代码,并且您的代码需要是可移植的,那么您必须进行更多的错误检查。^{}文档建议在失败时使用字符串错误消息或整数1。在

^{pr2}$

对于成功退出:

import os
import sys

subcommand = sys.argv[1]

if subcommand == 'noop':
    try:
        sys.exit(os.EX_OK)
    except:
        sys.exit()

print(subcommand)

考虑到退出代码带来的额外复杂性,如果您实际上不需要它们,那么最好跳过它们。在

参见documentation for ^{}。在

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.

相关问题 更多 >