18

I'm aware of the %load function (formerly %loadpy) which loads the contents of a file (or URL, ...) into a new input cell (which can be executed afterwards).

I'm also aware of %less, %more and %pycat, which show the contents of a file in a pager (which means in the notebook it's shown in the split-window at the bottom of the screen).

Is there a (magic) command to load a file and show its content (with syntax highlighting) in an output cell?

I.e. something like the following but with syntax highlighting of the result:

with open('my_file.py', 'r') as f:
    print(f.read())

I want the file content to be stored with the .ipynb file but I don't want it to be executed when I do Cell -> Run All.

Is there a command similar to %psource which shows the source code in an output cell instead of a pager?

Matthias
  • 4,524
  • 2
  • 31
  • 50
  • 2
    For the record, I've just seen that there has been a Gist for that all along: https://gist.github.com/jiffyclub/5385501 – Matthias Mar 01 '18 at 19:19

3 Answers3

21

Example code based on answer by @Matt:

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython

with open('my_file.py') as f:
    code = f.read()

formatter = HtmlFormatter()
IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
    formatter.get_style_defs('.highlight'),
    highlight(code, PythonLexer(), formatter)))
jgosmann
  • 750
  • 9
  • 19
3

No there is not way to do that with current magics, but it is pretty easy using pygments and returning IPython.display.HTML(...).

Matt
  • 27,170
  • 6
  • 80
  • 74
3

10 years later, and there's now a much simpler solution: https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Code

from IPython.display import Code

Code(filename='my_file.py', language='python')
tvt173
  • 1,746
  • 19
  • 17