Debian Codegraph @

texmf-dist/doc/lualatex/pyluatex/pyluatex.tex

raw
1 \documentclass[a4paper]{article}
2 \usepackage{fontspec}
3 \setmainfont{TeX Gyre Heros}
4 \setmonofont{TeX Gyre Cursor}[Ligatures=NoCommon]
5 \usepackage[margin=3cm]{geometry}
6 \usepackage{parskip}
7 \linespread{1.1}
8 \usepackage[listings,breakable]{tcolorbox}
9 \tcbset{breakable,listing only,size=fbox,colframe=black!10,boxrule=3pt,
10 colback=black!10}
11 \NewDocumentCommand{\inlcode}{O{}v}{\texttt{#1#2}}
12 \usepackage[colorlinks=true,urlcolor=blue,linkcolor=blue]{hyperref}
13 \title{The \emph{pyluatex} package}
14 \author{Tobias Enderle\\\url{https://github.com/tndrle/PyLuaTeX}}
15 \date{v0.7.0 (2026/04/17)}
16 \begin{document}
17 \maketitle
18 \raggedright
19 \textbf{Execute Python code on the fly in your \LaTeX{} documents}
20
21 PyLuaTeX allows you to execute Python code and to include the resulting output
22 in your \LaTeX{} documents in a \textit{single compilation run}.
23 \LaTeX{} documents must be compiled with Lua\LaTeX{} for this to work.
24
25
26 \section{Example}\label{Example}
27 \begin{enumerate}
28 \item \LaTeX{} document \inlcode|example.tex|
29 \begin{tcblisting}{}\documentclass{article}
30
31 \usepackage{pyluatex}
32
33 \begin{python}
34 import math
35 import random
36
37 random.seed(0)
38
39 greeting = 'Hello PyLuaTeX!'
40 \end{python}
41
42 \newcommand{\randint}[2]{\py{random.randint(#1, #2)}}
43
44 \begin{document}
45 \py{greeting}
46
47 $\sqrt{371} = \py{math.sqrt(371)}$
48
49 \randint{2}{5}
50 \end{document}
51 \end{tcblisting}
52 \item Compile using Lua\LaTeX{} (shell escape is required)
53 \begin{tcblisting}{}lualatex --shell-escape example.tex
54 \end{tcblisting}
55 \end{enumerate}
56 \textbf{Note:} PyLuaTeX starts Python 3 using the command \inlcode|python3| by default.
57 If \inlcode|python3| does not start Python 3 on your system, find the correct command
58 and extend \inlcode|\usepackage{pyluatex}| to
59 \inlcode|\usepackage[executable=<your python command>]{pyluatex}|.
60 For example, \inlcode|\usepackage[executable=python.exe]{pyluatex}|.
61
62 \textbf{Security note:} Running \LaTeX{} with the \inlcode|--shell-escape| option
63 allows arbitrary code to be executed.
64 For this reason, it is recommended to \textbf{compile trusted documents only}.
65
66 \subsection{Further Examples}\label{Further Examples}
67 The folder \inlcode|example| contains additional example documents:
68 \begin{itemize}
69 \item \inlcode|beamer.tex|\par
70 Demonstrates the use of PyLuaTeX environments and typesetting in \textit{BEAMER}
71 presentations. In particular, the \inlcode|fragile| option for frames is highlighted.
72 \item \inlcode|data-visualization.tex|\par
73 Demonstrates the visualization of data using \textit{pgfplots} and \textit{pandas}
74 \item \inlcode|matplotlib-external.tex|\par
75 Demonstrates how \textit{matplotlib} plots can be generated and included in a
76 document
77 \item \inlcode|matplotlib-pgf.tex|\par
78 Demonstrates how \textit{matplotlib} plots can be generated and included in a
79 document using \textit{PGF}
80 \item \inlcode|readme-example.tex|\par
81 The example above
82 \item \inlcode|repl.tex|\par
83 Demonstrates how a Python console/REPL can be run and typeset
84 \item \inlcode|sessions.tex|\par
85 Demonstrates the use of different Python sessions in a document
86 \item \inlcode|typesetting-example.tex|\par
87 The code typesetting example below
88 \item \inlcode|typesetting-listings.tex|\par
89 A detailed example for typesetting code and output with the \textit{listings}
90 package
91 \item \inlcode|typesetting-minted.tex|\par
92 A detailed example for typesetting code and output with the \textit{minted} package
93 \end{itemize}
94 \section{Reference}\label{Reference}
95 \subsection{Commands}\label{Commands}
96 Most of the following commands accept key-value options.
97 See \nameref{Options} for more details.
98
99 \begin{itemize}
100 \item \inlcode[\bfseries]|\py[<options>]{<code>}|\par
101 Executes (object-like) \inlcode|<code>| and writes its string representation to
102 the document.\par
103 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
104 \textit{Example:} \inlcode|\py{3 + 7}|
105 \item \inlcode[\bfseries]|\pyc[<options>]{<code>}|\par
106 Executes \inlcode|<code>|. Output (e.g. from a call to \inlcode|print()|) is written to
107 the document.\par
108 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
109 \textit{Examples:} \inlcode|\pyc{x = 5}|, \inlcode|\pyc{print('hello')}|
110 \item \inlcode[\bfseries]|\pyfile[<options>]{<path>}|\par
111 Executes the Python file specified by \inlcode|<path>|.
112 Output (e.g. from a call to \inlcode|print()|) is written to the document.\par
113 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
114 \textit{Example:} \inlcode|\pyfile{main.py}|
115 \item \inlcode[\bfseries]|\pyif[<options>]{<test>}{<then clause>}{<else clause>}|\par
116 Evaluates the Python boolean expression \inlcode|<test>|, and then executes either
117 the \LaTeX{} code in \inlcode|<then clause>| or the \LaTeX{} code in \inlcode|<else clause>|.\par
118 \textit{Allowed options:} \inlcode|session|, \inlcode|verbose|\par
119 \textit{Example:} \inlcode|\pyif{a == 1}{$a = 1$}{$a \neq 1$}|
120 \item \inlcode[\bfseries]|\pyoptions{<options>}|\par
121 Sets options globally.
122 For more information see the \nameref{Options} section.\par
123 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
124 \textit{Example:} \inlcode|\pyoptions{verbose,session=main}|
125 \end{itemize}
126 The following commands exist as shortcuts and for backward compatibility with
127 previous versions of PyLuaTeX:
128
129 \begin{itemize}
130 \item \inlcode[\bfseries]|\pyq[<options>]{<code>}|\par
131 Executes (object-like) \inlcode|<code>|. Any output to the document is suppressed.\par
132 This is equivalent to \inlcode|\py[quiet,<options>]{<code>}|.\par
133 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
134 \textit{Example:} \inlcode|\pyq{3 + 7}|
135 \item \inlcode[\bfseries]|\pycq[<options>]{<code>}|\par
136 Executes \inlcode|<code>|. Any output to the document is suppressed.\par
137 This is equivalent to \inlcode|\pyc[quiet,<options>]{<code>}|.\par
138 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
139 \textit{Example:} \inlcode|\pycq{x = 5}|
140 \item \inlcode[\bfseries]|\pyfileq[<options>]{<path>}|\par
141 Executes the Python file specified by \inlcode|<path>|. Any output to the
142 document is suppressed.\par
143 This is equivalent to \inlcode|\pyfile[quiet,<options>]{<path>}|.\par
144 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
145 \textit{Example:} \inlcode|\pyfileq{main.py}|
146 \item \inlcode[\bfseries]|\pysession{<name>}|\par
147 Sets \inlcode|<name>| globally as Python session for subsequent Python code.
148 The session that is active at the beginning is \inlcode|default|.\par
149 This is equivalent to \inlcode|\pyoptions{session=<name>}|.\par
150 \textit{Example:} \inlcode|\pysession{main}|
151 \item \inlcode[\bfseries]|\pyoption{<option>}{<value>}|\par
152 Assigns \inlcode|<value>| to the option \inlcode|<option>| globally.
153 For more information see the \nameref{Options} section.\par
154 This is equivalent to \inlcode|\pyoptions{<option>=<value>}|.\par
155 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
156 \textit{Example:} \inlcode|\pyoption{verbose}{true}|
157 \end{itemize}
158 \subsection{Environments}\label{Environments}
159 \begin{itemize}
160 \item \inlcode[\bfseries]|python|\par
161 Executes the provided block of Python code.
162 The environment handles characters like \inlcode|_|, \inlcode|#|, \inlcode|%|, \inlcode|\|, etc.
163 Code on the same line as \inlcode|\begin{python}| is ignored, i.e., code must
164 start on the next line.
165 If leading spaces are present, they are gobbled automatically up to the
166 first level of indentation.\par
167 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|quiet|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|\par
168 \textit{Example:}
169 \begin{tcblisting}{}\begin{python}
170 x = 'Hello PyLuaTeX'
171 print(x)
172 \end{python}
173 \end{tcblisting}
174 \end{itemize}
175 Like commands, environments accept key-value options, e.g.
176 \begin{tcblisting}{}\begin{python}[ignoreerrors]
177 print(1 / 0)
178 \end{python}
179 \end{tcblisting}
180 The opening tag \inlcode|[| must \textbf{directly follow} the \inlcode|\begin{python}|.
181 Spaces or line breaks between \inlcode|\begin{python}| and \inlcode|[| are not allowed.
182
183 The following environments exist as shortcuts and for backward
184 compatibility with previous versions of PyLuaTeX:
185
186 \begin{itemize}
187 \item \inlcode[\bfseries]|pythonq|\par
188 Same as the \inlcode|python| environment, but any output to the document is
189 suppressed.\par
190 This is equivalent to \inlcode|\begin{python}[quiet,<options>]|.\par
191 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|repl|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|
192 \item \inlcode[\bfseries]|pythonrepl|\par
193 Executes the provided block of Python code in an interactive console/REPL.
194 Code and output are stored together in the output buffer and can be
195 typeset as explained in the section \nameref{Typesetting Code}
196 or as shown in the example \inlcode|repl.tex| in the folder \inlcode|example|.\par
197 This is equivalent to \inlcode|\begin{python}[quiet,repl,<options>]|.\par
198 \textit{Allowed options:} \inlcode|ignoreerrors|, \inlcode|session|, \inlcode|store|, \inlcode|verbose|
199 \end{itemize}
200 \subsection{Custom Environments}\label{Custom Environments}
201 You can create your own environments based on the \inlcode|python|, \inlcode|pythonq| and
202 \inlcode|pythonrepl| environments.
203 However, since those are verbatim environments, you have to use the command
204 \inlcode|\PyLTVerbatimEnv| in your environment definition, e.g.
205 \begin{tcblisting}{}\NewDocumentEnvironment{custompy}{}
206 {\PyLTVerbatimEnv\begin{python}}
207 {\end{python}}
208 \end{tcblisting}
209
210 \subsection{Options}\label{Options}
211 Options marked with \textit{package option only} are only valid as package
212 options in \inlcode|\usepackage[...]{pyluatex}|.
213 All other options can be used as package options and throughout the
214 document.
215 Options can be set globally using \inlcode|\pyoptions| or locally for the
216 various environments and commands.
217 If a value contains commas, the entire value must be enclosed in
218 quotation marks.
219
220 \begin{itemize}
221 \item \inlcode[\bfseries]|executable| \quad{} \inlcode|string| \quad{} \textit{default:} \inlcode|python3| \quad{} \textit{package option only}\par
222 Specifies the path to the Python executable.\par
223 \textit{Example:} \inlcode|\usepackage[executable=/usr/local/bin/python3]{pyluatex}|
224 \item \inlcode[\bfseries]|ignoreerrors| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|false|\par
225 By default, PyLuaTeX aborts the compilation process when Python reports an
226 error. If the \inlcode|ignoreerrors| option is set, the compilation process is not
227 aborted.\par
228 \textit{Alias:} \inlcode|ignore errors|\par
229 \textit{Examples:} \inlcode|\usepackage[ignoreerrors]{pyluatex}|, \inlcode|\py[ignore errors]{1 / 0}|
230 \item \inlcode[\bfseries]|localimports| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|true| \quad{} \textit{package option only}\par
231 If this option is set, the folder containing the \LaTeX{} input file is added
232 to the Python path. This allows local Python packages to be imported.\par
233 \textit{Alias:} \inlcode|local imports|\par
234 \textit{Example:} \inlcode|\usepackage[localimports=false]{pyluatex}|
235 \item \inlcode[\bfseries]|quiet| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|false|\par
236 If this option is set, any output to the document is suppressed, even if
237 the Python code explicitly calls \inlcode|print()|. This is helpful if you want
238 to process code or output further and do your own typesetting. For an
239 example, see the \nameref{Typesetting Code} section.\par
240 \textit{Alias:} \inlcode|q|\par
241 \textit{Examples:} \inlcode|\py[quiet]{7 + 4}|, \inlcode|\py[q]{'Hello'}|
242 \item \inlcode[\bfseries]|repl| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|false|\par
243 If this option is set, Python code is executed in an interactive
244 console/REPL. Code and output are stored together in the output buffer
245 and can be typeset as explained in the section
246 \nameref{Typesetting Code} or as shown in the example
247 \inlcode|repl.tex| in the folder \inlcode|example|. The use of \inlcode|quiet| together with
248 \inlcode|repl| is recommended.
249 \item \inlcode[\bfseries]|session| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|default|\par
250 Sessions provide a way to structure and separate code.
251 Variables, function definitions, etc. of one session are only accessible
252 by that session. This can be helpful in long documents
253 with a lot of code.\par
254 \textit{Alias:} \inlcode|s|\par
255 \textit{Examples:} \inlcode|\pyc[session=main]{x = 5}|, \inlcode|\py[s=main]{x}|
256 \item \inlcode[\bfseries]|shutdown| \quad{} \inlcode|choice| \quad{} \textit{default:} \inlcode|veryveryend| \quad{} \textit{package option only}\par
257 Specifies when the Python process is shut down.\par
258 \textit{Possible values:} \inlcode|veryveryend|, \inlcode|veryenddocument|, \inlcode|off|\par
259 PyLuaTeX shuts down the Python interpreter when the compilation is done.
260 With the option \inlcode|veryveryend|, Python is shut down in the
261 \inlcode|enddocument/end| hook. With the option \inlcode|veryenddocument|, Python is shut
262 down in the \inlcode|enddocument/afteraux| hook. With the option \inlcode|off|, Python is
263 not shut down explicitly. However, the Python process will shut down when
264 the LuaTeX process finishes even if \inlcode|off| is selected. Using \inlcode|off| on
265 Windows might lead to problems with SyncTeX, though
266 (\href{https://github.com/tndrle/PyLuaTeX/issues/8}{https://github.com/tndrle/PyLuaTeX/issues/8}).\par
267 Before v0.6.2, PyLuaTeX used the hooks \inlcode|\AtVeryVeryEnd| and
268 \inlcode|\AtVeryEndDocument| of the package \textit{atveryend}. The new hooks
269 \inlcode|enddocument/end| and \inlcode|enddocument/afteraux| are equivalent to those of
270 the \textit{atveryend} package.\par
271 \textit{Example:} \inlcode|\usepackage[shutdown=veryenddocument]{pyluatex}|
272 \item \inlcode[\bfseries]|store| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|true|\par
273 If this option is set, code and output are stored in buffers.
274 See \nameref{Typesetting Code} for more details.\par
275 \textit{Example:} \inlcode|\pyc[store=false]{x = 5}|
276 \item \inlcode[\bfseries]|verbose| \quad{} \inlcode|boolean| \quad{} \textit{default:} \inlcode|false|\par
277 If this option is set, Python input and output is written to the \LaTeX{} log
278 file.\par
279 \textit{Examples:} \inlcode|\usepackage[verbose]{pyluatex}|, \inlcode|\py[verbose]{7 + 4}|
280 \end{itemize}
281 \subsection{Logging from Python}\label{Logging from Python}
282 \begin{tcblisting}{}tex.log(*objects, sep=' ', end='\n')
283 \end{tcblisting}
284 Writes \inlcode|objects| to the \LaTeX{} log, separated by \inlcode|sep| and followed by \inlcode|end|.
285 All elements in \inlcode|objects| are converted to strings using \inlcode|str()|.
286 Both \inlcode|sep| and \inlcode|end| must be strings.
287
288 \textit{Example:}
289 \begin{tcblisting}{}\begin{python}
290 tex.log('This text goes to the LaTeX log.')
291 \end{python}
292 \end{tcblisting}
293
294 \section{Requirements}\label{Requirements}
295 \begin{itemize}
296 \item Lua\LaTeX{}
297 \item Python 3
298 \item Linux, macOS or Windows
299 \end{itemize}
300 \section{Typesetting Code}\label{Typesetting Code}
301 Sometimes, in addition to having Python code executed and the output written
302 to your document, you also want to show the code itself in your document.
303 PyLuaTeX does not offer any commands or environments that directly typeset code.
304 However, PyLuaTeX has a \textbf{code and output buffer} which you can use to create
305 your own typesetting functionality.
306 This provides a lot of flexibility for your typesetting.
307
308 After a PyLuaTeX command or environment has been executed, the corresponding
309 Python code and output can be accessed via the Lua functions
310 \inlcode|pyluatex.get_last_code()| and \inlcode|pyluatex.get_last_output()|, respectively.
311 Both functions return a Lua \href{https://www.lua.org/pil/2.5.html}{table}
312 (basically an array) where each table item corresponds to a line of code
313 or output.
314
315 A simple example for typesetting code and output using the \textit{listings} package
316 would be:
317 \begin{tcblisting}{}\documentclass{article}
318
319 \usepackage{pyluatex}
320 \usepackage{listings}
321 \usepackage{luacode}
322
323 \begin{luacode}
324 function pytypeset()
325 tex.print("\\begin{lstlisting}[language=Python]")
326 tex.print(pyluatex.get_last_code())
327 tex.print("\\end{lstlisting}")
328 tex.print("") -- ensure newline
329 end
330 \end{luacode}
331
332 \newcommand*{\pytypeset}{%
333 \noindent\textbf{Input:}
334 \directlua{pytypeset()}
335 \textbf{Output:}
336 \begin{center}
337 \directlua{tex.print(pyluatex.get_last_output())}
338 \end{center}
339 }
340
341 \begin{document}
342
343 \begin{python}[quiet]
344 greeting = 'Hello PyLuaTeX!'
345 print(greeting)
346 \end{python}
347 \pytypeset
348
349 \end{document}
350 \end{tcblisting}
351
352 Notice that we use the \inlcode|python| environment with the \inlcode|quiet| option,
353 which suppresses any output.
354 After that, the custom command \inlcode|\pytypeset| is responsible for typesetting
355 the code and its output.
356
357 Using a different code listings package like \textit{minted}, or typesetting inline
358 code is very easy.
359 You can also define your own environments that combine Python code and
360 typesetting. See the \inlcode|typesetting-*.tex| examples in the \inlcode|example| folder.
361
362 Use the option \inlcode|repl|, to emulate an interactive Python console/REPL.
363
364 \section{How It Works}\label{How It Works}
365 PyLuaTeX runs a Python \href{https://docs.python.org/3/library/code.html#code.InteractiveInterpreter}{\inlcode[\color{blue}]|InteractiveInterpreter|}
366 (actually several if you use different sessions) in the background for
367 on-the-fly code execution. Python code from your \LaTeX{} file is sent to the
368 background interpreter through a TCP socket. This approach allows your
369 Python code to be executed and the output to be integrated in your \LaTeX{}
370 file in a single compilation run. No additional processing steps are needed.
371 No intermediate files have to be written. No placeholders have to be inserted.
372
373 \section{License}\label{License}
374 \href{http://www.latex-project.org/lppl.txt}{LPPL 1.3c} for \LaTeX{} code and
375 \href{https://opensource.org/licenses/MIT}{MIT license} for Python and Lua code
376 and other files.
377 \end{document}