prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.11k stars 717 forks source link

How to get formatted text? #1739

Open sdaqo opened 1 year ago

sdaqo commented 1 year ago

Hello! I am currently stuck on trying to get the formatted text. Is there any easy way to do that?

I tried a lot and came up with this, but it is not perfect . After calling the get_formatted_text function twice, I get a I/O operation on closed file error.

from prompt_toolkit import print_formatted_text, HTML
from io import StringIO
import sys

# set isatty to True so create_output does not create a PlainTextOutput
class TtyStringIO(StringIO):
    def isatty(self) -> bool:
        return True

def get_formatted_text(text):
    with TtyStringIO() as str_io:
        sys.stdout = str_io
        print_formatted_text(HTML(text))
        sys.stdout = sys.__stdout__
        val = str_io.getvalue()
    return val

# This Works as expected
print(get_formatted_text("<b>Hello World</b>"))
# This fails with a ValueError: I/O operation on closed file
print(get_formatted_text("Hello World"))
c-holtermann commented 10 months ago

I'm interested in this as well as I'd like to use the formatted text with tqdm.write().