gpt4 book ai didi

Python 因逻辑错误而退出

转载 作者:行者123 更新时间:2023-12-01 03:51:41 25 4
gpt4 key购买 nike

在我的代码中,我试图处理逻辑错误。如果我执行 sys.exit(1),我想退出程序并显示错误代码它会引发回溯错误,这是我不想要的。但是,如果我这样做os._exit(1)它不是清洁导出。

我的需求:像 os 一样退出仅包含错误代码,但需要像 sys 那样更干净的退出.

最佳答案

无论如何都要使用sys.exit(1)sys.excepthook() 中的标准 Python 回溯 Hook 干净地处理 SystemExit,不打印回溯。来自 SystemExit exception documentation :

This exception is raised by the sys.exit() function. When it is not handled, the Python interpreter exits; no stack traceback is printed.

我的粗体强调。

如果您的程序有顶级异常处理程序,请不要捕获SystemExit。通常,您不使用一揽子 except: 语句,而是通过捕获 except Exception: 来实现这一点。

关于Python 因逻辑错误而退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38140196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com