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}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}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.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}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 * xPitfalls
- A file that does not exist stops the compile run with the error "Package Listings Error: File ... not found". Check the path and the spelling, including upper and lower case.
- With pdfLaTeX, a file that contains umlauts or other non-ASCII characters needs the
literatesetting shown in Insert source code in LaTeX. - To print a file without highlighting,
\verbatiminput{file}from theverbatimpackage is enough; see Verbatim text in LaTeX.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
listings - How-to Insert source code in LaTeX
- How-to Verbatim text in LaTeX
- How-to Split a document into multiple files in LaTeX
- Error Couldn't load requested language
- Package
xcolor