Debian Codegraph @

texmf-dist/doc/latex/pythonimmediate/pythonimmediate.tex

raw
1 \ProvidesFile{pythonimmediate.tex}[2025/08/24 0.6.0 Library to run Python code]
2 \RequirePackage{fvextra}
3 \documentclass{l3doc}
4 \usepackage{tikz}
5 \usetikzlibrary{calc}
6 \usetikzlibrary{arrows.meta}
7 \EnableCrossrefs
8 \CodelineIndex
9 \fvset{breaklines=true,breakanywhere,gobble=0,tabsize=4,frame=single,numbers=left,numbersep=3pt}
10 \usepackage{cleveref}
11
12 \AtBeginDocument{\DeleteShortVerb\"} % https://tex.stackexchange.com/a/650966/250119
13 \MakeOuterQuote{"}
14
15 \newcommand\reg{régime}
16 \newcommand\DescribePython{\DescribeMacro} % hack
17
18
19 \begin{document}
20
21 \hfuzz=15pt
22
23 % hack to make quotes inside |...| straight
24 \edef\temp{\def\noexpand|{\noexpand\Verb\string|}}\temp
25 % basically execute \def| { \Verb ⟨catcode other |⟩ }
26
27 \GetFileInfo{\jobname.tex}
28
29 \title{\pkg{\jobname} --- \fileinfo
30 \thanks{This file describes version \fileversion, last revised \filedate.}
31 }
32 \author{user202729}
33 \date{Released \filedate}
34
35 \maketitle
36
37 \section{Motivation}
38
39 Just like \pkg{Perl\TeX} or \pkg{PyLua\TeX} (and unlike \pkg{Python\TeX} or \pkg{lt3luabridge}),
40 this only requires a single run, and variables are persistent throughout the run.
41
42 Unlike \pkg{Perl\TeX} or \pkg{PyLua\TeX}, there's no restriction on compiler or script required to run the code.
43
44 There's also debugging functionalities -- \TeX\ errors results in Python traceback, and Python error results in \TeX\ traceback.
45 Errors in code executed with the |pycode| environment gives the correct traceback point to the Python line of code in the \TeX\ file.
46
47 For advanced users, this package allows the user to manipulate the \TeX\ state directly from within Python,
48 so you don't need to write a single line of \TeX\ code.
49
50 \section{Installation}
51
52 %You need to install Python \pkg{daemoniker} and \pkg{psutil} package.
53
54 In addition to the \LaTeX\ package, you need the Python \pkg{pythonimmediate-tex} package,
55 installation instruction can be found at \url{https://pypi.org/project/pythonimmediate-tex/}.
56
57 Note that not all \TeX\ package versions are compatible with all Python package versions.
58 This \TeX\ package is compatible with Python package version |0.7.2|.
59
60 Remember to enable unrestricted\footnote{
61 There's little point in supporting restricted mode, since it's possible to execute arbitrary shell commands in Python anyway.
62 If it's needed to execute untrusted \TeX\ code, separate sandboxing should be used.
63 } shell-escape. (there's a guide on \TeX.SE if necessary: \url{https://tex.stackexchange.com/q/598818/250119})
64
65 \subsection{Installation on Overleaf}\label{installation-on-overleaf}
66
67 At the point of writing, this package can be used on Overleaf.
68
69 Nevertheless, you cannot use |pip| to install Python packages on Overleaf directly, instead it's possible to
70 download |.zip| file, include it in your Overleaf project, and specify where the package can be found to Python
71 using |PYTHONPATH| environment variable.
72
73 Instruction:
74
75 \begin{itemize}
76 \item Download the following files and place it in the root folder of Overleaf:
77 \begin{itemize}
78 \item \file{pythonimmediate.sty}
79 \item \file{pythonimmediate_helper.lua}
80 \item \file{pythonimmediate_tex-0.7.2.zip}
81 \end{itemize}
82 The |0.7.2| part should be replaced with the desired version
83 of the Python package.
84
85 The |.sty| files can be downloaded from CTAN at
86 \url{https://ctan.org/pkg/pythonimmediate}.
87
88 The |.zip| file containing Python source code
89 can be downloaded from PyPI: \url{https://pypi.org/project/pythonimmediate-tex/\#files}.
90
91 Remark: Currently the \LaTeX\ package version 0.4.0 is included in \TeX\ Live 2023, you would need to download \LaTeX\ version 0.5.0 from CTAN.
92
93 \item In older \TeX\ Live versions (2022 or less), you will in addition need to download the following files:
94 \begin{itemize}
95 \item \file{saveenv.sty} (from \url{https://ctan.org/pkg/saveenv}),
96 \item \file{precattl.sty} (from \url{https://ctan.org/pkg/precattl}).
97 \end{itemize}
98 Also place in the root folder of Overleaf.
99
100 \item Write the following in the preamble (be careful of stray characters if you copy and paste from PDF):
101 \begin{verbatim}
102 \usepackage[abspath]{currfile}
103 \usepackage[python-executable={PYTHONPATH=pythonimmediate_tex-0.7.2.zip/pythonimmediate_tex-0.7.2/ python3},args={--mode=unnamed-pipe}]{pythonimmediate}
104 \end{verbatim}
105 As above, replace both occurrences of |0.7.2| with the downloaded version specified in the zip file above.
106
107 Refer to \cref{troubleshoot-source-file-not-found} for explanation of the |abspath| option.
108 \end{itemize}
109
110 For some unknown reason in the default mode on Overleaf (|\nonstopmode|), when there's an error
111 the log file might be truncated,
112 so in that case consider writing |\errorstopmode|.
113
114 Refer to \cref{troubleshoot-Python-error} to read the error traceback in case of Python error.
115
116 Some construct inside the |pycode| block might make the code editor on Overleaf report an error,
117 even though the code is valid. Refer to \url{https://www.overleaf.com/learn/how-to/Code_Check#Code_Check_Limitations}.
118
119 \section{Usage}
120
121 \subsection{Package options}
122
123 Normally no options are required.
124 If you're not sure what they do, just use the default options.
125
126 \DescribeOption{args=}
127 Arguments to be passed to the Python component of the program. Run
128 \begin{verbatim}
129 python -m pythonimmediate.pytotex --help
130 \end{verbatim}
131 on the command-line to view the available options.
132
133 The documentation is also available at
134 \url{https://pythonimmediate.readthedocs.io/en/latest/pythonimmediate.html#module-pythonimmediate.pytotex}.
135
136 \DescribeOption{python-executable=}
137 The name/path to the Python executable. Default to |python3|.
138
139 Can also be used to provide environment variables to the Python process.
140 An example how to do that is explained in \cref{installation-on-overleaf}.
141
142 \DescribeOption{python-flags=}
143 Flags to be passed to the Python interpreter. For example pass |-O| to disable assertions.
144
145 The documentations can be found by running |python --help| on the command-line,
146 or visit \url{https://docs.python.org/3/using/cmdline.html}.
147
148 \subsection{\TeX\ interface}
149
150 The interface mimics those in popular packages such as \pkg{Python\TeX} or \pkg{PyLua\TeX}.
151
152 \subsubsection{Inline commands}
153
154 \DescribeMacro{\py}\label{py-command}
155 Evaluate some Python expression, consider the result as a string, then execute the result as \TeX\ command.
156
157 \begin{texnote}
158 The command is not expandable, and the argument will be fully expanded with the active |~| set to |\relax|,
159 |\set@display@protect| executed and |\escapechar=-1|, then the result
160 passed to Python as a string.
161 \end{texnote}
162
163 Which, for the users who are not familiar with \TeX\ terminology, roughly means the following:
164 \begin{itemize}
165 \item the value can only be used to typeset text,
166 it must not be used to pass "values" to other \LaTeX\ commands.
167
168 The following is legal:
169 \begin{verbatim}
170 The value of $1+1$ is $\py{1+1}$.
171 \end{verbatim}
172 The following is illegal, as the result (2) can only be used to typeset text, not passed to another command that expect a "value":
173 \begin{verbatim}
174 \setcounter{abc}{\py{1+1}}
175 \end{verbatim}
176 A possible workaround is:
177 \begin{verbatim}
178 \py{ r'\\setcounter{abc}{' + str(1+1) + '}' }
179 \end{verbatim}
180 In this example it works without escaping the |{}| characters, but if the Python code has those unbalanced then you can escape them as mentioned below.
181
182 \item Special characters can be "escaped" simply by prefixing the character with backslash.
183
184 For example
185 \begin{verbatim}
186 \pyc{assert len('\ \ ')==2}
187 \pyc{assert ord('\\\\')==0x5c}
188 \pyc{assert ord('\%') ==0x25}
189 \end{verbatim}
190 In the examples above, Python "sees" (i.e. the Python code being executed is)
191 \begin{verbatim}
192 assert len(' ')==2
193 assert ord('\\')==0x5c
194 assert ord('%') ==0x25
195 \end{verbatim}
196 respectively.
197
198 \item Macros will be expanded.
199 \begin{verbatim}
200 \def\mycode{1+1}
201 The value of $1+1$ is $\py{\mycode}$.
202 \end{verbatim}
203 \end{itemize}
204
205
206 \DescribeMacro{\pyc}
207 Execute some Python code provided as an argument (the argument will be interpreted as described above).
208
209 The command is not expandable -- roughly speaking, you can only use this at "top level".
210
211 Any output (as described in \cref{print-to-TeX}) will be typesetted.
212
213 The difference between |\py| and |\pyc| is that the argument of |\py| should be a Python expression
214 (suitable for passing into |eval()| Python function) while the argument of |\pyc| should be a Python
215 statement (suitable for passing into |exec()| Python function).
216
217 Therefore,
218 \begin{itemize}
219 \item |\py{1+1}| will typeset 2.
220 \item |\pyc{1+1}| is valid, but will do nothing just like |exec("1+1")|.
221 \item |\py{x=1}| is invalid.
222 \item |\pyc{x=1}| is valid and assigns the variable |x| to be 1.
223 \end{itemize}
224
225 \DescribeMacro{\pycq}
226 Same as above, but output (\cref{print-to-TeX}) will not be typesetted.
227
228 \DescribeMacro{\pyfile}
229 Given an argument being the file name, execute that file.
230
231 \DescribeMacro{\pys}
232 Performs "string interpolation", the same way as \pkg{Python\TeX}.
233 (not yet implemented)
234
235 \subsubsection{Environments}
236
237 \DescribeEnv{pycode}
238 Verbatim-like environment that executes the code inside as Python.
239
240 Example usage: The following will typeset |123|
241 \begin{verbatim}
242 \begin{pycode}
243 pythonimmediate.print("123")
244 \end{pycode}
245 \end{verbatim}
246
247 Special note: white spaces at the end of lines are preserved.
248
249 Any output (as described in \cref{print-to-TeX}) will be typesetted.
250
251 \DescribeEnv{pycodeq}
252 Same as above, but output will not be typesetted.
253
254 \DescribeEnv{pysub}
255 Not yet implemented.
256
257 \subsection{Python interface}
258
259 The \TeX\ interface is only used to call Python. Apart from that, all the work can be done on the Python side.
260
261 All functions in this section should be imported from |pythonimmediate| package, unless specified otherwise.
262
263 Currently, all the documentations are moved to the Python package documentation,
264 see \url{https://pythonimmediate.readthedocs.io/}.
265
266 Documentation of a few functions are still kept here for convenience, but \textbf{they might be outdated}.
267 Always refer to the online documentation.
268
269 \subsubsection{Print to \TeX}\label{print-to-TeX}
270
271 \DescribePython{.print_TeX()}
272 \DescribePython{.file}
273 These functions are used in |\pyc| command or |pycode| environment.
274
275 Unlike most other packages, using |print()| function in Python will print to the console (\TeX\ standard output).
276 In order to print \TeX\ code to be executed, you can do one of
277 \begin{verbatim}
278 pythonimmediate.print_TeX(...)
279 print(..., file=pythonimmediate.file)
280 with contextlib.redirect_stdout(pythonimmediate.file):
281 print(...)
282 \end{verbatim}
283 Note that in quiet environments, |pythonimmediate.file| is None, the second variant using |print()| will print to stdout
284 instead of suppress output. The third variant works as expected.
285
286 All output will be buffered until the whole Python code finishes executing.
287 In order to typeset the text immediately use one of the advanced commands.
288
289
290
291 \DescribePython{.newcommand()}
292 \DescribePython{.renewcommand()}
293 Same as \LaTeX's |\newcommand| and |\renewcommand|. Can be used as follows:
294
295 \begin{verbatim}
296 from pythonimmediate import newcommand, renewcommand
297
298 @newcommand
299 def function():
300 ...
301 # define |\function| in TeX
302
303 @newcommand("controlsequencename")
304 def function():
305 ...
306 # define |\controlsequencename| in TeX
307
308 def function():
309 ...
310 newcommand("controlsequencename", function)
311 \end{verbatim}
312
313 \DescribePython{.get_arg_str()}
314 \DescribePython{.get_optional_arg_str()}
315 \DescribePython{.get_verb_arg()}
316 \DescribePython{.get_multiline_verb_arg()}
317 \DescribePython{.peek_next_char()}
318 \DescribePython{.get_next_char()}
319 There are those functions that is mostly understandable to an inexperienced \LaTeX\ user,
320 and should be sufficient for a lot of programming works.
321
322 This is an example of how the functions could be used. The name should be mostly self-explanatory.
323
324 \begin{verbatim}
325 \documentclass{article}
326 \usepackage{pythonimmediate}
327 \begin{document}
328 \begin{pycode}
329 from pythonimmediate import newcommand, peek_next_char, get_next_char, get_arg_str
330 from pythonimmediate import print_TeX as print
331 @newcommand
332 def innerproduct():
333 s = get_arg_str() # in the example below this will have the value '\mathbf{a},\mathbf{b}'
334 x, y = s.split(",") # it's just a Python string, manipulate normally (but be careful of comma inside braces, parse the string yourself)
335 print(r"\left\langle" + x + r"\middle|" + y + r"\right\rangle")
336
337 @newcommand
338 def fx():
339 if peek_next_char() == "_":
340 get_next_char()
341 subscript = get_arg_str()
342 print("f_{" + subscript + "}(x)")
343 else:
344 print("f(x)")
345
346 @newcommand
347 def sumManyArgs():
348 s = 0
349 while peek_next_char() == "{":
350 i = get_arg_str()
351 s += int(i)
352 print(str(s))
353 \end{pycode}
354 $1+2+3 = \sumManyArgs{1}{2}{3}$
355
356 $\innerproduct{\mathbf{a},\mathbf{b}}=1$
357
358 $\fx = 1$, $\fx_i = 2$, $\fx_{ij} = 3$
359 \end{document}
360 \end{verbatim}
361
362 It will typeset:
363
364 \begin{quote}
365 $1+2+3=6$
366
367 $\left\langle\mathbf{a}\middle\vert\mathbf{b}\right\rangle=1$
368
369 $f(x)=1$, $f_i(x)=2$, $f_{ij}(x)=3$
370 \end{quote}
371
372 \DescribePython{.get_arg_estr()}
373 \DescribePython{.get_optional_arg_estr()}
374 Similar to some functions above, except that the argument is fully expanded and "escapes" of common characters are handled correctly,
375 similar to how |\py| command (\cref{py-command}) reads its arguments.
376
377 \DescribePython{.execute()}
378 Takes a string and execute it immediately. (so that any |.execute()| will be executed before any |.print_TeX()|)
379
380 Assuming \TeX\ is in errorstopmode (i.e. errors halt \TeX\ execution),
381 any error in \TeX\ will create an error in Python and the traceback should point to the correct line of code.
382
383 For example, in the following code
384
385 \begin{verbatim}
386 \documentclass{article}
387 \usepackage{tikz}
388 \usepackage{pythonimmediate}
389 \begin{document}
390
391 \begin{tikzpicture}
392 \begin{pycode}
393 from pythonimmediate import execute
394 execute(r'\draw (0, 0) to (1, 1);')
395 execute(r'\draw (2, 2) to (p);')
396 execute(r'\draw (3, 3) to (4, 4);')
397 \end{pycode}
398 \end{tikzpicture}
399
400 \end{document}
401 \end{verbatim}
402 each |\draw| command will be executed immediately when the Python |.execute()| function is executed,
403 and as the second line throws an error, the Python traceback will point to that line.
404
405 \section{Troubleshooting}
406
407 \subsection{"Incompatible TeX package version" error message}\label{troubleshoot-incompatible-version}
408 Exactly what it means. You can upgrade both the Python package and the TeX package to the latest version.
409
410 Alternatively, you can also \emph{downgrade} whichever package that is newer. For instance, Python package version 0.5.0 (download from \url{https://pypi.org/project/pythonimmediate-tex/0.5.0/#files}) is compatible with \LaTeX\ package version 0.4.0.
411
412 \subsection{"Source file not found!" error message}\label{troubleshoot-source-file-not-found}
413
414 In order to obtain the exact code with trailing spaces and produce error traceback
415 point to the correct \TeX\ file, the Python code need to know the full path to the current
416 \TeX\ file for the |pycode| environment.
417
418 Nevertheless, this is difficult and does not always work
419 (refer to the documentation of \pkg{currfile} for details), so this message is issued
420 when the file cannot be found.
421
422 In that case try the following fixes:
423
424 \begin{itemize}
425 \item Include |\usepackage[abspath]{currfile}| at the start of the document, after the |\documentclass| line.
426 (this option is not included by default because it's easy to get package clash, and usually \pkg{currfile} without
427 the |abspath| option works fine -- unless custom |jobname| is used)
428 \item Explicitly override |currfilename| or |currfileabspath| -- for example
429 \begin{verbatim}
430 \def\currfilename{main.tex}
431 \end{verbatim}
432 Technically this is an abuse of the \pkg{currfile} package API, but it usually works regardless.
433 \end{itemize}
434
435 \subsection{"Python error" error message}\label{troubleshoot-Python-error}
436
437 In case of Python error, the Python traceback is included in the terminal and \TeX\ log file.
438
439 Search for "Python error traceback" before the error line in the log file.
440
441 On Overleaf, you can either view the log file ("Raw logs" section)
442 or the traceback on stderr (download \file{output.stderr} file)
443
444 \subsection{"\TeX\ error" error message}\label{troubleshoot-TeX-error}
445
446 If an error occur in \TeX, traceback cannot be included in the log file.
447
448 Besides, this can only be detected in |\errorstopmode|. Such an error will always halt \TeX,
449 and Python will be force-exited after printing the error traceback.
450
451 On Overleaf, download \file{output.stderr} file to read the traceback.
452
453 \section{Implementation note}
454
455 Communication between \TeX\ and Python are done by opening two pseudo-files from the output of a Python process |textopy|
456 (similar to |\ior_shell_open:Nn|)
457 and to the input of another Python process |pytotex| (this would be |\iow_shell_open:Nn|, if \LaTeX3 have such a function).
458
459 There are various methods for the 2 Python child processes to communicate with each other.
460 After some initial bootstrapping to setup the communication, we can consider only the |textopy| script, the other
461 merely serves as the bridge to send input to \TeX.
462
463 The communication protocol is a little complicated, since it must support nesting bidirectional execution of \TeX\ and Python.
464
465 Besides, I believe it's not possible to make a "background listener" on the \TeX\ side, so it must keep track of whether a command should be read from Python and executed.
466
467 Currently, exception handling (throwing a Python exception in a nested Python function, catch it in the outer Python function) is not supported.
468
469 These are some examples of what could happen in the communication protocol.
470
471 \ExplSyntaxOn
472 \let\fpEval\fp_eval:n
473 \ExplSyntaxOff
474
475 \begingroup
476
477 \tikzset{myarrow/.style={-{Latex[length=2mm]}}}
478
479 \def\blockWidth{1}
480 \def\blockHeight{7}
481 \def\separation{10.5}
482 \def\step{0.7}
483
484 \def\left #1{
485 \draw [myarrow] (p) ++(\separation, 0) -- node [above] {\small #1} ++(-\separation, 0);
486 \path (p) ++ (0, -\step) coordinate (p);
487 }
488 \def\right #1{
489 \draw [myarrow] (p) -- node [above] {\small #1} ++(\separation, 0);
490 \path (p) ++ (0, -\step) coordinate (p);
491 }
492
493 \def\initDrawing{
494 \path (\blockWidth, \fpEval{-\step}) coordinate (p);
495 }
496
497 \newdimen \tempx
498 \newdimen \tempy
499
500 \ExplSyntaxOn
501 \let \dimToDecimalInUnit \dim_to_decimal_in_unit:nn
502 \ExplSyntaxOff
503
504 \def\drawBlocks{
505 \path [transform canvas] (p);
506 \pgfgetlastxy{\tempx}{\tempy}
507 \edef\blockHeight{ \fpEval{ - \dimToDecimalInUnit{\tempy}{1cm} } }
508
509 \draw (0, \fpEval{-\blockHeight}) rectangle node [rotate=90] {\TeX} (\blockWidth, 0);
510 \draw (\fpEval{\blockWidth+\separation}, \fpEval{-\blockHeight}) rectangle node [rotate=270] {Python} (\fpEval{\separation+2*\blockWidth}, 0);
511 }
512
513 \vspace{5pt}
514 \begin{tikzpicture}
515 \edef\blockHeight{\fpEval{\step*3}}
516 \initDrawing
517 \right{execute Python code: print(1)}
518 \left{execute \TeX\ code: 1}
519 \drawBlocks
520 \end{tikzpicture}
521
522 Nevertheless, there may be more complicated cases where the Python code itself may call \TeX\ code before actually returns:
523
524 \vspace{5pt}
525 \begin{tikzpicture}
526 \edef\blockHeight{\fpEval{\step*5}}
527 \initDrawing
528 \right{execute Python code: print(var(a)*2)}
529 \left{execute \TeX\ code: sendtopy(a); execute another command}
530 \right{123}
531 \left{execute \TeX\ code: 123123}
532 \drawBlocks
533 \end{tikzpicture}
534
535 Or:
536
537 \vspace{5pt}
538 \begin{tikzpicture}
539 \edef\blockHeight{\fpEval{\step*7}}
540 \initDrawing
541 \right{execute Python code: tex.exec(a=456); print(var(a)*2)}
542 \left{execute \TeX\ code: a=456; sendtopy(done); execute another command}
543 \right{done}
544 \left{execute \TeX\ code: sendtopy(a); execute another command}
545 \right{456}
546 \left{456456}
547 \drawBlocks
548 \end{tikzpicture}
549
550 \endgroup
551
552 The Python side must not just listen for "done" command back, but must potentially call a nested loop.
553
554 The exact protocol is:
555 \begin{itemize}
556 \item "execute Python code" sends from \TeX\ to Python has a single line "|i|\meta{handler name}",
557 followed by any number of arguments (depends on the handler).
558
559 Refer to the |define_TeX_call_Python| internal function for details.
560
561 \item "done" sends from \TeX\ to Python has the format "|r|\meta{optional return value as a string in a single line}".
562
563 This is sent by executing \TeX\ command |\pythonimmediatecontinue|, which takes a single argument to be e-expanded using |\write|
564 as the "return value".
565
566 \item "execute \TeX\ code" sends from Python to \TeX\ must only be sent when the \TeX\ side listens for a command.
567 It consist of a single line specify the "command name", which \TeX\ will
568 execute the command named
569 |\__run_|\meta{command name}|:|
570 which must already be defined on the \TeX\ side.
571
572 The command itself might contain additional code to execute more code, e.g. by reading more lines from Python.
573
574 Refer to the |define_Python_call_TeX| internal function for details.
575 \end{itemize}
576
577
578
579 \PrintIndex
580
581 \end{document}