Skip to content
Advertisement

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:

JavaScript

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

JavaScript

Desired normal output:

JavaScript

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

Advertisement

Answer

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

JavaScript

Use your flag to determine the behaviour.

Example:

JavaScript

The nicer way is to use and exception hook:

JavaScript

Edit:

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

JavaScript

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement