Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show (as output cell) the contents of a .py file with syntax highlighting?

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?

like image 632
Matthias Avatar asked Oct 05 '13 12:10

Matthias


People also ask

How do I read a .py file in Jupyter notebook?

load python file in jupyter notebook A text file can be loaded in a notebook cell with the magic command %load. the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

Can I run .py file in Jupyter notebook directly?

py file from jupyter? Some simple options: Open a terminal in Jupyter, run your Python scripts in the terminal like you would in your local terminal. Make a notebook, and use %run <name of script.py> as an entry in a cell.

How do I run a text file in a Jupyter notebook?

Click New —> Python 3 menu item to create a new Jupyter notebook file (. ipynb file). Input below ipython code in the first cell line, then click the Run button to run it to create file abc. txt and write text data to it.


2 Answers

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)))
like image 109
jgosmann Avatar answered Nov 03 '22 00:11

jgosmann


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

like image 39
Matt Avatar answered Nov 03 '22 00:11

Matt