prompt-toolkit / prompt-toolkit/python-prompt-toolkit

How to get formatted text?

Open
#1,739 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
10.6k
Forks
815
PR merge metrics
No merged PRs in 30d

Description

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"))

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the closed-file error with the provided get_formatted_text example, then inspect print_formatted_text and its output handling. Done means repeated calls return the formatted text without raising an I/O operation on closed file error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.