Use Pygments
to make the stack trace a little more beautiful.
sample_code.py
def funcA():
funcB()
def funcB():
funcC()
def fucnC():
1/0 # error!
funcA()
↓ It looks like this when it is raw
Traceback (most recent call last):
File "test.py", line 10, in <module>
funcA()
File "test.py", line 2, in funcA
funcB()
File "test.py", line 5, in funcB
funcC()
NameError: name 'funcC' is not defined
↓ I want to make it as beautiful as this
Traceback (most recent call last):
File "test.py", line 10, in <module>
funcA()
File "test.py", line 2, in funcA
funcB()
File "test.py", line 5, in funcB
funcC()
NameError: name 'funcC' is not defined
Whether it's pip
, ʻeasy_install, or
port`.
pip install Pygments
Use sys.excepthook
.
coloring.py
import sys
def myexcepthook(type, value, tb):
import traceback
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
tbtext = ''.join(traceback.format_exception(type, value, tb))
lexer = get_lexer_by_name("pytb", stripall=True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext, lexer, formatter))
sys.excepthook = myexcepthook
Reference: Coloring exceptions from Python on a terminal
For the time being, the character string and numerical value of the stack trace output by this will be colored.
It's a hassle to add the above to all the code, so let's do it for yourself. _ (It can lead to bugs that don't make sense, so it's a good idea to understand what you're doing before trying.) _
Use ʻuser customize`. Reference: 16.1.4. Modules for customization
Create ʻusercustomize.py in the directory output by
python -c "import site; print (site.getusersitepackages ())" and write the above code
coloring.py` and you're done.
The feeling of trying it and the ease of understanding do not change much! !!
Recommended Posts