Include source code from a file in LaTeX (lstinputlisting)

\lstinputlisting[language=Python]{example.py} from the listings package reads a source file and prints it as a listing. LaTeX reads the file at every compile run, so the document always shows the current code.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{listings}
\usepackage{xcolor}

Include a whole file

The argument is the file name, relative to the folder of the main .tex file. The options are the same as for the lstlisting environment.

\lstinputlisting[language=Python, basicstyle=\ttfamily\small]{example.py}
Result
The compiled example

Open in the editor

Include some lines only

firstline and lastline select a range of lines; linerange={1-1,3-5} selects several ranges. The line numbers in the output start at 1 in both cases. firstnumber=3 makes them start at 3, which matches the numbers in the file here.

\lstinputlisting[language=Python, basicstyle=\ttfamily\small,
  firstline=3, lastline=5, numbers=left, firstnumber=3]{example.py}
Result
The compiled example

Open in the editor

Add a caption and a label

caption and label number the listing and make it available to \ref and to \lstlistoflistings.

\lstinputlisting[language=Python, basicstyle=\ttfamily\small,
  caption={Area of a circle}, label={lst:area}]{example.py}

Listing~\ref{lst:area} shows the complete file.
Result
The compiled example

Open in the editor

Use one style and one folder for all files

\lstdefinestyle stores a set of options under a name, and \lstset{style=...} turns it on for every listing. inputpath=src tells \lstinputlisting to look for the files in the folder src, so tool.py stands for src/tool.py.

Complete document:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstdefinestyle{code}{
  language=Python,
  basicstyle=\ttfamily\small,
  keywordstyle=\color{blue},
  commentstyle=\color{gray},
  numbers=left,
  frame=single,
  breaklines=true
}
\lstset{style=code, inputpath=src}
\begin{document}
\lstinputlisting{tool.py}
\end{document}
Result
The compiled example

Open in the editor

File example.py:

import math

def area(radius):
    """Return the area of a circle."""
    return math.pi * radius ** 2

print(area(2))

File src/tool.py:

def double(x):
    return 2 * x

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages