Random ramblings about Mac, Python, TeX, programming, and more   |     |        |     |  



Including source code in papers (and exams)

November 17, 2019  |  publ, python, programming

In march 2015, I wrote about using Pygments when including source code in papers (and on the web). I still use Pygments, but I have never updated the description on how I do it now. In most cases, I use Pygments implicitly without interacting with the program myself. I leave it to the LaTeX package minted. You still need to install Pygments, but you do not need to interact with it. The minted package calls Pygments to do the task for you. The only thing you have to do is to ensure that LaTeX or PDFLaTeX (or whatever version of LaTeX you are using) is passed the --shell-escape option. Otherwise, LaTeX is not allowed to do such calls.

I often use minted in combination with the LaTeX package fancyvrb. For example, in this excerption from a LaTeX document:

\usepackage{fancyvrb}
\usepackage{minted}
  ⁝
The function \mintinline{python}{dblderivative} should be used
like this:

  \inputminted[firstline=2]{python}{dblderivative-ex.py}

The execution of this example will give the following output:

  \VerbatimInput[label=Resultat fra kjøring]{dblderivative-ex.out}

In the preamble, I load the two LaTeX packages. The \inputminted command will include the Python code from the file dblderivative.py pretty-printed in the document in the selected style. You can use the command \usemintedstyle to change the style of the code included in the document. To list possible styles run the following command in a shell:

pygmentize -L styles

The default style is inspired by Emacs. The \VerbatimInput command in the example will include the text file dblderivative-ex.out with a nice layout in the document, including a descriptive text (label). In this example, the text file is generated from running the Python program dblderivative-ex.py piping the output from the program to the text file:

python dblderivative-ex.py > dblderivative-ex.out

This example above can typically end up looking like this in the final PDF document:

Minted ex

You can also include code directly in LaTeX using the minted environment:

\begin{minted}{python}
def dblderivative(f, x, h=1E-5):
    return (f(x + h) - 2*f(x) + f(x - h))/h**2
\end{minted}

More detailed description of the usage of these packages can be found in the minted documentation and in the fancyvrb documentation.

Last updated: June 22, 2024