Skip to content

Instantly share code, notes, and snippets.

@jgosmann
Created February 6, 2014 22:15
Show Gist options
  • Save jgosmann/8853594 to your computer and use it in GitHub Desktop.
Save jgosmann/8853594 to your computer and use it in GitHub Desktop.
Code to include formatted sources in IPython notebooks.
# Some code do include nicely formatted source code listings of external
# files. Unfortunately, these listings will not be included using
# nbconvert to convert the notebook to a PDF.
import IPython
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
def include_listing(filename):
with open(filename) as f:
code = f.read()
formatter = HtmlFormatter()
return IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, PythonLexer(), formatter)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment