sys.exit(1)不工作,脚本以代码0结束

2024-10-01 13:32:24 发布

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

我有以下代码:

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结尾:

script-exit-code

我做错了什么


Tags: the代码self脚本ifstatuswith结尾
1条回答
网友
1楼 · 发布于 2024-10-01 13:32:24

如果在脚本顶层有类似的内容,它将阻止sys.exit()退出程序:

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

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

相关问题 更多 >