sys.exit(1) 无效,脚本以代码 0 结束

sys.exit(1) not working, the script ends with code 0

我有以下代码:

try:
    self._collect_persons_status()
except manager.AsteriskManagerError:
    # If it is not possible to continue with the collection of initial
    # person statuses via Asterisk Manager, end the program with an
    # error code.
    logger.debug('*** exit with 1!!')
    sys.exit(1)

此脚本通过 systemd 处理(作为带循环的守护进程运行)。

从日志中我可以看到打印了 *** exit with 1!!,但脚本以代码 0 结束,而不是预期的 1:

我做错了什么?

如果您在脚本顶层有这样的东西,它将阻止 sys.exit() 退出程序:

try:
    <invoke script entry point>
except:
    <log the error>

这是因为 sys.exit() 是通过引发 SystemExit 异常实现的。您可以通过将 except: 更改为 except Exception 来修复代码,这不会捕获 SystemExit (以及您可能不想处理的其他一些低级异常)。