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