简体   繁体   中英

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?

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, eg 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 eg:

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM