Can't print pyinstrument's output in Streamlit

Hello guys!

I would like to print PyInstrument’s output in Streamlit, but it doesn’t seem to work.

For context, Pyinstrument is a Python profiler ->

Here’s a screenshot of the code:

So print(profiler.output_text(unicode=True, color=True)) prints the desired output to the terminal (#2 in screenhost above)

yet its streamlit transalation via st.write -> st.write(profiler.output_text(unicode=True, color=True)) doesn’t print properly in Streamlit, see screenshot below::

Here’s the corresponding code:

Do you know if there would be a workaround for this?

Thanks in advance :slight_smile:

Hello @Charly_Wargnier,

As profiler.output_text() is meant to be printed in a console, when you enable colors, it uses ANSI color codes. You have two ways to display such output:

1. Strip ANSI codes and display the result with st.code()

import re

# ... your code ...

profiler_output = profiler.output_text(unicode=True, color=True)

# Regex source:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")

result = ansi_escape.sub("", profiler_output)

2. Convert ANSI codes to HTML with ansi2html

You’ll first have to do a pip install ansi2html.

from ansi2html import Ansi2HTMLConverter
import streamlit.components.v1 as components

# ... your code ...

profiler_output = profiler.output_text(unicode=True, color=True)

ansi_converter = Ansi2HTMLConverter()
html_output = ansi_converter.convert(profiler_output)

components.html(html_output, height=300, scrolling=True)

With this last method, you’ll have to fix a height.

If fixing the height is an issue, another solution would be to create a real component and use a specific javascript library to automatically adjust the height as I do in all my components now.

1 Like

Thanks Synode! It works like a charm! :slight_smile:

1 Like