在python中为自定义异常设置退出代码 [英] Setting an exit code for a custom exception in python
问题描述
我正在使用自定义异常将我的异常与Python的默认异常区分开。
I'm using custom exceptions to differ my exceptions from Python's default exceptions.
当引发异常时,是否可以定义自定义退出代码?
Is there a way to define a custom exit code when I raise the exception?
class MyException(Exception):
pass
def do_something_bad():
raise MyException('This is a custom exception')
if __name__ == '__main__':
try:
do_something_bad()
except:
print('Oops') # Do some exception handling
raise
在此代码中, main函数在try代码中运行一些函数。
捕获异常后,我想重新引发它以保留回溯堆栈。
In this code, the main function runs a few functions in a try code. After I catch an exception I want to re-raise it to preserve the traceback stack.
问题是'raise'总是退出1。
我想使用自定义退出代码(针对我的自定义异常)退出脚本,并在其他情况下退出1。
The problem is that 'raise' always exits 1. I want to exit the script with a custom exit code (for my custom exception), and exit 1 in any other case.
我已经看过此解决方案但这不是我想要的东西:
在引发异常时在Python中设置退出代码
I've looked at this solution but it's not what I'm looking for: Setting exit code in Python when an exception is raised
此解决方案迫使我检查使用的每个脚本中的默认值还是默认值
This solution forces me to check in every script I use whether the exception is a default or a custom one.
我希望我的自定义异常能够告诉抬高函数使用哪种退出代码。
I want my custom exception to be able to tell the raise function what exit code to use.
推荐答案
您可以覆盖 sys.excepthook
做自己想做的事情:
You can override sys.excepthook
to do what you want yourself:
import sys
class ExitCodeException(Exception):
"base class for all exceptions which shall set the exit code"
def getExitCode(self):
"meant to be overridden in subclass"
return 3
def handleUncaughtException(exctype, value, trace):
oldHook(exctype, value, trace)
if isinstance(value, ExitCodeException):
sys.exit(value.getExitCode())
sys.excepthook, oldHook = handleUncaughtException, sys.excepthook
这样,您可以将此代码放在一个特殊的模块中您所有的代码都只需要导入。
This way you can put this code in a special module which all your code just needs to import.
这篇关于在python中为自定义异常设置退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!