Hide traceback unless a debug flag is set

前端 未结 2 528
面向向阳花
面向向阳花 2020-12-02 12:22

What is the idiomatic python way to hide traceback errors unless a verbose or debug flag is set?

Example code:

their_md5 = \'c38f03d2b7160f891fc36ec         


        
相关标签:
2条回答
  • 2020-12-02 12:41

    The short way is using the sys module and use this command:

    sys.tracebacklimit = 0
    

    Use your flag to determine the behaviour.

    Example:

    >>> import sys
    >>> sys.tracebacklimit=0
    >>> int('a')
    ValueError: invalid literal for int() with base 10: 'a'
    

    The nicer way is to use and exception hook:

    def exception_handler(exception_type, exception, traceback):
        # All your trace are belong to us!
        # your format
        print "%s: %s" % (exception_type.__name__, exception)
    
    sys.excepthook = exception_handler
    

    Edit:

    If you still need the option of falling back to the original hook:

    def exception_handler(exception_type, exception, traceback, debug_hook=sys.excepthook):
        if _your_debug_flag_here:
            debug_hook(exception_type, exception, traceback)
        else:
            print "%s: %s" % (exception_type.__name__, exception)
    

    Now you can pass a debug hook to the handler, but you'll most likely want to always use the one originated in sys.excepthook (so pass nothing in debug_hook). Python binds default arguments once in definition time (common pitfall...) which makes this always work with the same original handler, before replaced.

    0 讨论(0)
  • 2020-12-02 12:53
    try:
        pass # Your code here
    except Exception as e:
        if debug:
            raise # re-raise the exception
                  # traceback gets printed
        else:
            print("{}: {}".format(type(e).__name__, e))
    
    0 讨论(0)
提交回复
热议问题