| 1 |
%% Copyright 2021-2026 Tobias Enderle |
| 2 |
%% |
| 3 |
%% This work may be distributed and/or modified under the |
| 4 |
%% conditions of the LaTeX Project Public License, either version 1.3c |
| 5 |
%% of this license or (at your option) any later version. |
| 6 |
%% The latest version of this license is in |
| 7 |
%% http://www.latex-project.org/lppl.txt |
| 8 |
%% and version 1.3c or later is part of all distributions of LaTeX |
| 9 |
%% version 2005/12/01 or later. |
| 10 |
|
| 11 |
% DESCRIPTION |
| 12 |
% Demonstrates how a Python console/REPL can be run and typeset |
| 13 |
|
| 14 |
\documentclass{article} |
| 15 |
|
| 16 |
\usepackage{pyluatex} |
| 17 |
\usepackage{listings} |
| 18 |
\usepackage{xcolor} |
| 19 |
\lstset{ |
| 20 |
language=Python, |
| 21 |
breaklines=true, |
| 22 |
framesep=1ex, |
| 23 |
frame=lrtb, |
| 24 |
framerule=0pt, |
| 25 |
numbers=none, |
| 26 |
basicstyle=\ttfamily, |
| 27 |
keywordstyle=\bfseries\color{green!40!black}, |
| 28 |
stringstyle=\bfseries\color{red!80!black}, |
| 29 |
identifierstyle=\color{blue}, |
| 30 |
backgroundcolor=\color{gray!10!white}, |
| 31 |
} |
| 32 |
\usepackage{luacode} |
| 33 |
|
| 34 |
\begin{luacode} |
| 35 |
function pytypeset() |
| 36 |
tex.print("\\begin{lstlisting}") |
| 37 |
tex.print(pyluatex.get_last_output()) |
| 38 |
tex.print("\\end{lstlisting}") |
| 39 |
end |
| 40 |
\end{luacode} |
| 41 |
|
| 42 |
\newcommand{\pytypeset}{\directlua{pytypeset()}} |
| 43 |
|
| 44 |
\NewDocumentEnvironment{pyrepl}{} |
| 45 |
{\PyLTVerbatimEnv\begin{python}[repl,quiet]} |
| 46 |
{\end{python}\pytypeset} |
| 47 |
|
| 48 |
\begin{filecontents*}[nosearch]{repl.py} |
| 49 |
def square(x): |
| 50 |
return x**2 |
| 51 |
|
| 52 |
square(5) |
| 53 |
\end{filecontents*} |
| 54 |
|
| 55 |
\begin{document} |
| 56 |
|
| 57 |
PyLuaTeX allows you to run and typeset Python code in an interactive console |
| 58 |
or read–eval–print loop (REPL) fashion. Much like in an interactive Python session, |
| 59 |
code is prefixed with \verb|>>>| (or \verb|...| in case of multi-line commands) |
| 60 |
and the results are added to the output buffer automatically. |
| 61 |
|
| 62 |
Both code and output are stored in PyLuaTeX's output buffer and can be accessed |
| 63 |
by \verb|pyluatex.get_last_output()|. In this way, you can adjust the typesetting |
| 64 |
to your needs. For examples of typesetting, see \verb|typesetting-listings.tex| |
| 65 |
and \verb|typesetting-minted.tex|. |
| 66 |
|
| 67 |
In the following example, we use the custom environment \verb|pyrepl|, which is |
| 68 |
based on the \verb|python| environment provided by PyLuaTeX with the options |
| 69 |
\verb|repl| and \verb|quiet|. |
| 70 |
\begin{pyrepl} |
| 71 |
def fun(): |
| 72 |
print('Hello PyLuaTeX!') |
| 73 |
|
| 74 |
3 + 1 *\ |
| 75 |
4 |
| 76 |
fun() |
| 77 |
\end{pyrepl} |
| 78 |
|
| 79 |
Python sessions can also be read from files: |
| 80 |
\pyfile[repl,quiet]{repl.py} |
| 81 |
\pytypeset |
| 82 |
|
| 83 |
\end{document} |