为了账号安全,请及时绑定邮箱和手机立即绑定

python: traceback.print_stack(): 如何着色和重新格式化输出

python: traceback.print_stack(): 如何着色和重新格式化输出

波斯汪 2022-05-19 15:54:48
我想查看代码的完整跟踪,直到某个特定点所以我愿意...import tracebacktraceback.print_stack()...然后会显示  File ".venv/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__    return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)  File ".venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1052, in results_iter    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)  File ".venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql    cursor.execute(sql, params)  File ".venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 110, in execute    extra={'duration': duration, 'sql': sql, 'params': params}  File "/usr/lib64/python3.7/logging/__init__.py", line 1371, in debug    self._log(DEBUG, msg, args, **kwargs)  File "/usr/lib64/python3.7/logging/__init__.py", line 1519, in _log    self.handle(record)  File "/usr/lib64/python3.7/logging/__init__.py", line 1528, in handle    if (not self.disabled) and self.filter(record):  File "/usr/lib64/python3.7/logging/__init__.py", line 762, in filter    result = f.filter(record)  File "basic_django/settings.py", line 402, in filter    traceback.print_stack()如何使用 pygments 使这个输出更加丰富多彩。通常我会在 python 中为 json 字符串着色from pygments import highlightfrom pygments.lexers import JsonLexerfrom pygments.formatters import TerminalTrueColorFormatterjson_str = '{ "name":"John" }'print(highlight(json_str, JsonLexer(), TerminalTrueColorFormatter()))同样如何做到这一点traceback.print_stack()
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

Pygments 列出了可用的词法分析器。你可以用 Python3TracebackLexer 做到这一点。


from pygments import highlight

from pygments.lexers import Python3TracebackLexer

from pygments.formatters import TerminalTrueColorFormatter


err_str = '''

  File ".venv/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__

    return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

  File ".venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1052, in results_iter

    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)

  File ".venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql

    cursor.execute(sql, params)

  File ".venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 110, in execute

    extra={'duration': duration, 'sql': sql, 'params': params}

  File "/usr/lib64/python3.7/logging/__init__.py", line 1371, in debug

    self._log(DEBUG, msg, args, **kwargs)

  File "/usr/lib64/python3.7/logging/__init__.py", line 1519, in _log

    self.handle(record)

  File "/usr/lib64/python3.7/logging/__init__.py", line 1528, in handle

    if (not self.disabled) and self.filter(record):

  File "/usr/lib64/python3.7/logging/__init__.py", line 762, in filter

    result = f.filter(record)

  File "basic_django/settings.py", line 402, in filter

    traceback.print_stack()

'''


print(highlight(err_str, Python3TracebackLexer(), TerminalTrueColorFormatter()))

为了得到err_str,替换print_stack为format_stack如下:


def colorize_traceback(err_str):

    return highlight(err_str, Python3TracebackLexer(), TerminalTrueColorFormatter())


try:

    ... # Some logic

except Exception:   # Or a more narrow exception

    # tb.print_stack()

    print(colorize_traceback(tb.format_stack()))


查看完整回答
反对 回复 2022-05-19
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

或者,使用丰富的库。

只需两行代码,它将美化您的回溯......然后一些!

from rich.traceback import install
install()

之后看起来如何?看一眼:

//img1.sycdn.imooc.com//6285f7f40001894112381207.jpg

和它的美丽?它支持 Pygment 主题

查看完整回答
反对 回复 2022-05-19
  • 2 回答
  • 0 关注
  • 257 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信