sys.exit(1) 不起作用,脚本以代码 0 结尾

lor*_*ile 2 python systemd

我有以下代码:

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)
Run Code Online (Sandbox Code Playgroud)

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

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

脚本退出代码

我究竟做错了什么?

use*_*342 5

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

try:
    <invoke script entry point>
except:
    <log the error>
Run Code Online (Sandbox Code Playgroud)

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

  • 我会使用“ except Exception”,它不会捕获现有的异常。 (2认同)
  • @timgeb 好主意;我现在修改了答案,建议不要明确地使用“ except SystemExit”。 (2认同)