How to silence “sys.excepthook is missing” error?

后端 未结 4 2035
再見小時候
再見小時候 2020-12-02 16:59

NB: I have not attempted to reproduce the problem described below under Windows, or with versions of Python other than 2.7.3.

The most reliable way to elicit the pro

4条回答
  •  臣服心动
    2020-12-02 17:21

    In your program throws an exception that can not be caught using try/except block. To catch him, override function sys.excepthook:

    import sys
    sys.excepthook = lambda *args: None
    

    From documentation:

    sys.excepthook(type, value, traceback)

    When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

    Illustrative example:

    import sys
    import logging
    
    def log_uncaught_exceptions(exception_type, exception, tb):
    
        logging.critical(''.join(traceback.format_tb(tb)))
        logging.critical('{0}: {1}'.format(exception_type, exception))
    
    sys.excepthook = log_uncaught_exceptions
    

提交回复
热议问题