Monday, March 30, 2020

Will McGugan: Rich adds support for Jupyter Notebooks

I recently added experimental support for Jupyter Notebooks to Rich. Here's an example of the kind of output it can generate:

© 2020 Will McGugan

This is the Rich test card you can generate in the terminal with python -m rich.

© 2020 Will McGugan

Part 2 of the Rich test card.

Rich is a library for fancy formatting to the terminal, where-as Jupyter supports HTML natively. So why integrate one with the other? I suspect it may be useful to render something like a table in the terminal which also displays nicely in Jupyter.

Jupyter does convert ANSI codes for style / colour etc in to HTML, which is nice. But it didn't work with Jupyter initially, because Jupyter replaces stdout with a file object that captures output, and that that object doesn't declare itself as a terminal capable device. It also broke tables and any other formatting that assumes a fix grid, because the browser wraps output which caused misalignment of box characters. Fortunately I was able to workaround both those issues.

You can try this out by doing from rich.jupyter import print within Jupyter. This will give the print function a few super-powers:

from rich.jupyter import print
print("Hello, [green bold]World![/] :ninja:")

Now you can insert colour and style in to your output. Rich will pretty print Python data structures with syntax highlighting, and you can render of the renderables supported by Rich.

I'm not sure how useful this is to anyone. I had barely used Jupyter before Sunday afternoon, but if it is useful please tweet @willmcgugan and let me know. I'm not sure if its worth making this an official part of the Rich API, or just leave it as a novelty I hacked up to avoid boredom while self-distancing.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...