Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide traceback unless a debug flag is set

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

Example code:

their_md5 = 'c38f03d2b7160f891fc36ec776ca4685' my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7'  if their_md5 != my_md5:     raise ValueError('md5 sum does not match!') 

Existing output now, but only desired when called with foo.py --debug:

Traceback (most recent call last):   File "b:\code\apt\apt.py", line 1647, in <module>     __main__.__dict__[command] (packages)   File "b:\code\apt\apt.py", line 399, in md5     raise ValueError('md5 sum does not match!') ValueError: md5 sum does not match! 

Desired normal output:

ValueError: md5 sum does not match! 

Here's a test script: https://gist.github.com/maphew/e3a75c147cca98019cd8

like image 410
matt wilkie Avatar asked Dec 28 '14 07:12

matt wilkie


People also ask

How do I fix Python traceback error?

If there is no variable defined with that name you will get a NameError exception. To fix the problem, in Python 2, you can use raw_input() . This returns the string entered by the user and does not attempt to evaluate it. Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

What is traceback Print_exc ()?

If type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error. traceback. print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys.

What are common traceback errors?

Some of the common traceback errors are:IndexError. KeyError. TypeError. valueError.


1 Answers

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.

like image 190
Reut Sharabani Avatar answered Oct 15 '22 00:10

Reut Sharabani