Last active
May 31, 2023 10:03
-
-
Save BlackHC/f5e2449035f0e47c9c038bb080bebe81 to your computer and use it in GitHub Desktop.
Render HTML to IPython terminals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# !pip install rich markdownify | |
# https://chat.openai.com/share/5f3f2019-2051-4217-93ea-c926fa3c2749 | |
import markdownify | |
from IPython.core.getipython import get_ipython | |
from IPython.display import HTML | |
from rich import print | |
from rich.console import Console | |
from rich.markdown import Markdown | |
def print_html(obj): | |
# Create a Rich console that outputs to a string | |
console = Console() | |
# Convert the HTML to Markdown | |
markdown = markdownify.markdownify(obj.data) | |
rich_markdown = Markdown(markdown) | |
console.print(rich_markdown) | |
if __name__ == "__main__": | |
# Create InteractiveShell instance | |
from IPython.core.interactiveshell import InteractiveShell | |
InteractiveShell.instance() | |
# Get the current IPython instance | |
ipython = get_ipython() | |
if ipython is not None: | |
# Register the renderer for HTML objects | |
ipython.display_formatter.ipython_display_formatter.for_type(HTML, print_html) | |
if __name__ == "__main__": | |
print( | |
ipython.display_formatter.format( | |
HTML( | |
"<h1>Hello World</h1><p>This is a paragraph</p><ul><li>Item 1</li><li>Item 2</li></ul>" | |
) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment