1

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))
ntg
  • 12,950
  • 7
  • 74
  • 95

1 Answers1

1

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

ntg
  • 12,950
  • 7
  • 74
  • 95
saloua
  • 2,433
  • 4
  • 27
  • 37
  • Nice answer (+1) I will add a second part with details on how to call with a string and will accept it if there is no better answer (without calling processes) I like that this can be used for languages other than python as well! – ntg Nov 23 '20 at 21:07