我想要做的就是在 Panel 小部件中显示一个 asci 字符串并保留其格式/颜色

问题描述

我想要做的就是在 Panel 小部件中显示一个 asci 字符串并保留其格式/颜色。

我想要的:

#here's the string after pygments formatting:
test = '\x1b[38;2;0;68;221mTraceback (most recent call last):\x1b[39m\n  File \x1b[38;2;0;128;0m"<ipython-input-3-39b4fbfd5961>"\x1b[39m,line \x1b[38;2;102;102;102m17\x1b[39m,in <module>\n    myfunc(\x1b[38;2;102;102;102m3\x1b[39m)\n  File \x1b[38;2;0;128;0m"<ipython-input-3-39b4fbfd5961>"\x1b[39m,line \x1b[38;2;102;102;102m6\x1b[39m,in myfunc\n    \x1b[38;2;0;128;0;01mreturn\x1b[39;00m myfunc(x\x1b[38;2;102;102;102m-\x1b[39m\x1b[38;2;102;102;102m1\x1b[39m)\n  File \x1b[38;2;0;128;0m"<ipython-input-3-39b4fbfd5961>"\x1b[39m,line \x1b[38;2;102;102;102m5\x1b[39m,in myfunc\n    \x1b[38;2;0;128;0;01massert\x1b[39;00m x \x1b[38;2;102;102;102m>\x1b[39m \x1b[38;2;102;102;102m0\x1b[39m,\x1b[38;2;186;33;33m"\x1b[39m\x1b[38;2;186;33;33moh no\x1b[39m\x1b[38;2;186;33;33m"\x1b[39m\n\x1b[38;2;255;0;0mAssertionError\x1b[39m: oh no\n'

#I want it to look like this in Panel:
print(test)

我有什么:

#The closest I can get is:
import panel as pn
string_b4_pygments = 'Traceback (most recent call last):\n  File "<ipython-input-3-39b4fbfd5961>",line 17,in <module>\n    myfunc(3)\n  File "<ipython-input-3-39b4fbfd5961>",line 6,in myfunc\n    return myfunc(x-1)\n  File "<ipython-input-3-39b4fbfd5961>",line 5,in myfunc\n    assert x > 0,"oh no"\nAssertionError: oh no\n'
pn.pane.Str(string_b4_pygments)

解决方法

我发现捕获错误并将其格式化为 html 而不是 asci 可以解决问题。例如

import panel as pn
import traceback as tb
from pygments import highlight
from pygments.lexers import Python3TracebackLexer
from pygments.formatters import HtmlFormatter
pn.extension()

def myfunc(x):
   assert x > 0,"oh no"
   return myfunc(x-1)

def extract_format_tb_html(e):
    traceback_str = ''.join(tb.format_exception(None,e,e.__traceback__))
    return highlight(traceback_str,Python3TracebackLexer(),HtmlFormatter(noclasses=True))

try:
    myfunc(3)
except Exception as e:
    test = extract_format_tb_html(e)

pn.pane.Str(test)