Setting an exit code for a custom exception in python

十年热恋 提交于 2019-12-01 03:48:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!