0

All I want to do is display an asci string in a Panel widget and retain its formatting/color.

What I Want:

#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;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;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)

What I Have:

#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 6, in myfunc\n    return myfunc(x-1)\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)
itwasthekix
  • 585
  • 6
  • 11

1 Answers1

0

I found that capturing the error and formatting it as an html instead of asci did the trick. E.g.

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)
itwasthekix
  • 585
  • 6
  • 11