Script display from an external file in Jupyter Notebook with syntax-highlighting

Viewed 1013

I am making a tutorial using Jupyter and I would like to display the content of an external Python script. Printing the content of the file is trivial, but I am interested in a color-coded/syntax-highlighted text (either in a markdown cell or as an output).

2 Answers

Use Ipython's Markdown module:

from IPython.display import Markdown as md

script = """
x = 2
if x*2 > 2:
    print('x > 2')
else:
    x = None
"""

md("```Python" + script + "```")

Will output:

enter image description here

One method is to use the magic command: %load

%load testLoad.py

This is assuming the external file is in your Jupyter Notebook starting directory

If you only want specific lines (say between lines 5 and 10 and also line 15) of your python code to be displayed then:

%load -r 5-10,15 testLoad.py

You can find out the options of a magic command by adding a '?' at the end of the magic command:

%load?

Magic commands are shortcuts that are used to help do things much faster in Jupyter Notebook. They are great for beginners as they generally contain everything a beginner needs to display and test Jupyter Notebook

Here is a link to all magic commands in IPython for Jupyter Notebook: https://ipython.readthedocs.io/en/stable/interactive/magics.html

Related