Search code examples
pythonpython-3.xshortcut

Build shortcut for `traceback.format_exc()`


So I use traceback.format_exc() like this:

try:
   # Some code
except:
   traceback_msg = '%s' % traceback.format_exc()
   print(traceback_msg)
   # Doing some stuff with it

pretty often in my code to output it to an additional file/stream and by writing code I am tired to keep typing it. Is there a simple way to define a global shortcut/ExceptionHandler which keeps care and is easy to call from various places?


Solution

  • You could use a module in a directory PYTHONPATH that imports under a shortened name (and itself has a short name).

    In your setup script set environment variable PYTHONPATH to point to a directory, e.g. in .bashrc in Linux, put

    export PYTHONPATH=/path/to/my_dir:$PYTHONPATH
    

    (You might want to do a test if any value already exists, and if not, suppress the colon here, but it's not critical.)

    and also create /path/to/my_dir/tb.py containing

    from traceback import format_exec as fe
    

    Then you could do interactively e.g.:

    >>> import tb
    >>> try:
    ...    a = 1 / 0
    ... except:
    ...    msg = tb.fe()
    ...    print(">>>", msg)
    

    to give

    >>> Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    ZeroDivisionError: division by zero
    

    Bear in mind though that your tb.py could conflict with another module also called tb.py that you are trying to use. Maybe for safety don't set PYTHONPATH all the time, but then (again Linux example here), set up an alias in your .bashrc.

    alias p='env PYTHONPATH=/path/to/my_dir:$PYTHONPATH python'

    so that it is only set when you launch python with the p alias.

    There is also an environment variable PYTHONSTARTUP which you can point at a script that runs whenever you start python, although not used in this example.