pretty print python code from jupyter notebook

1.9k views Asked by At

How to pretty print / display a piece of code from jupyter notebook, here is a (failing) example of what I am trying to do:

example

Ideally, I would ask for some other pprint that would print the code of foo with nice coloured annotation similar to how Jupyter notebook annotates the code in cell [1]

code of the example:

def foo():
    print(42)
import inspect
print(inspect.getsource(foo))
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(inspect.getsource(foo))
1

There are 1 answers

1
saloua On

If the code that you want to print out is in a separate script you can use the CLI pygments https://pygments.org/docs/cmdline/

In order to pretty print the code you just need to use the following

!pygmentize your_filename.py

So for Python 3.5+ (3.6+ for encoding), it would be:

def foo():
    print(42)

import inspect
from subprocess import check_output
from IPython.core.display import HTML

output = check_output(["pygmentize","-f","html","-O","full,style=emacs","-l","python"],
        input=inspect.getsource(foo), encoding='ascii')
HTML(output)

Refer to How do I pass a string into subprocess.Popen (using the stdin argument)? for other python versions.

enter image description here