PythonTeX (embed output)

PythonTeX (by Geoffrey M. Poore) is a package that actually runs the Python code you write inside your document at compile time and embeds the results back into the text. Plots, tables, and computed numbers live alongside the code that produced them — so there is no risk of mis-copying a value by hand, and editing the source and recompiling updates the results automatically. Besides Python it can also drive Ruby, Julia, R, Octave, and more.

What it does

Ordinary listings or minted only typeset code as it looks — they never run it (see “Code listings”). What sets PythonTeX apart is that it executes the code and pulls its output into the document. Write \py{2**10} in your text, and Python evaluates 2**10 so that the result 1024 is typeset right there. Write Python that draws a plot, and the generated figure appears as a figure.

Loading it is a single line, \usepackage{pythontex}. To run, you need Python itself, and syntax highlighting of the code uses Pygments (pip install pygments). Code runs in a separate process per “session,” and only the parts that changed are re-executed — so recompiling stays fast even when heavy computations are involved.

The commands and environments come as a family: a shared **base name (such as py) plus a suffix.** You pick among them by what you need — running one expression inline, running a whole block of code, also showing the code, or wanting only the result.

The main commands and environments

Start with the inline commands. \py{expr} sends the expression to Python and typesets its string representation (\py{2**10} → 1024). Besides curly braces, a matched pair of identical characters works too, so \py#2**10# and \py@2**10@ mean the same thing. It is for dropping a value into the text, so assignment is not allowed (\py{a=1} is invalid). Define a variable earlier and \py{a} brings back its value.

  • \py{expr} — run the expression and typeset its result (no suffix).
  • \pyc{code} — run it, but typeset nothing (c for code). Anything you print inside is pulled in.
  • \pyv{code} — do not run it; typeset the code verbatim (v for verb; same as pyverbatim).
  • \pyb{code}both run and typeset it (b for block). Printed output is not included automatically.
  • \pys{code} — string interpolation: replace each !{expr} with its evaluated result, then interpret the code as LaTeX (s for sub).

For multiple lines, use the environments. pycode runs its code but typesets nothing (ideal for computing or generating figures). pyverbatim typesets but does not run. pyblock both runs and typesets. pysub is the environment form of \pys (interpolating !{expr}). Printed output from pyblock or \pyb does not appear on its own, so place \printpythontex where you want it to bring that output in.

To show an interactive session, use the **pyconsole environment.** It treats each line as if typed into an interactive Python interpreter, reproducing the >>> prompt with input and output together. Its inline counterpart \pycon{code} runs the code and brings back only the output (discarding the input) — handy for referencing a console variable’s value.

A worked example

A typical flow: compute a value in a pycode environment, then use \py{…} in the prose to typeset it. Notice that the code and its result live entirely within one manuscript.

document.tex
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{pythontex}

\begin{document}
% 実行されるが、何も組版されない
\begin{pycode}
from math import sqrt
radius = 2.5
area = 3.14159 * radius**2
hyp = sqrt(3**2 + 4**2)
\end{pycode}

半径 \py{radius} の円の面積はおよそ \py{round(area, 2)} です。

\(2^{10} = \py{2**10}\)、また \(\sqrt{3^2+4^2} = \py{hyp}\)\end{document}

This reads “The area of a circle of radius 2.5 is about 19.63,” followed by the equations 2¹⁰ = 1024 and √(3²+4²) = 5.0. Change radius and rebuild, and every number in the prose moves with it.

The build pipeline (three steps)

A PythonTeX build has three stages. (1) Run the LaTeX engine (e.g. pdflatex) as usual; on this pass the code is not executed but extracted to an external file. (2) The bundled **pythontex program runs that extracted code and saves the results. (3) Run the LaTeX engine once more, and the saved results are pulled into** the document to make the PDF.

terminal
pdflatex document.tex    # 1) コードを抽出 / extract the code
pythontex document.tex   # 2) Python で実行 / run it with Python
pdflatex document.tex    # 3) 結果を取り込む / pull the output back in

This is the key point: the code is run not by LaTeX itself but by a **separate program, pythontex, in between. Because of that, the manual three-step build does not need --shell-escape** (this is exactly where it differs from minted, which shells out from inside LaTeX). When you instead want to automate it into a single compile with a tool like latexmk, a common setup enables -shell-escape so that the LaTeX pass can invoke pythontex. Declaring the dependency in .latexmkrc lets it run pythontex and recompile automatically whenever the code changes.

It works for Japanese documents too. Swap pdflatex for lualatex and the same three steps apply regardless of engine (Japanese platex works as well). When the code contains Unicode, set up the document’s encoding accordingly — under pdfLaTeX, \usepackage[T1]{fontenc} with \usepackage[utf8]{inputenc}; under LuaLaTeX, \usepackage{fontspec}.

The sympy and pylab families

By default, alongside the Python py family, two families aimed at scientific work are provided. Each just swaps the base name to sympy or pylab, giving the same lineup of commands — \sympy, sympycode, sympyblock and \pylab, pylabcode, pylabblock.

  • The sympy family — loads the symbolic-math library SymPy via from sympy import *. A result inserted with \sympy is formatted into context-aware LaTeX using SymPy’s LatexPrinter.
  • The pylab family — loads matplotlib’s pylab module via from pylab import *, putting plotting and NumPy in one namespace.

The families work side by side as independent sets of commands and environments. You might typeset an expression solved symbolically with SymPy as clean math via \sympy, while generating a matplotlib figure in pylabcode and including it with \includegraphics.

depythontex and safety

Because a PythonTeX document mixes LaTeX and Python, it is ill-suited to venues that reject special packages, or to conversion into other formats. That is where **depythontex** helps. Build with the package option depythontex enabled and an auxiliary file <jobname>.depytx is created; the depythontex.py script reconciles it with the original to produce a separate document in which every PythonTeX command and environment is replaced by the typeset code and its output. The result is plain, PythonTeX-free LaTeX with the results baked in — suitable for sharing or journal submission.

terminal
# 1) depythontex オプション付きで通常の 3 ステップを実行
#    Run the usual three steps with the depythontex option on
pdflatex document.tex
pythontex document.tex
pdflatex document.tex

# 2) 静的な版を書き出す(-o で出力名を指定)
#    Write the static version (-o gives the output name)
depythontex -o document-plain.tex document.tex

Finally, mind the security implication. Compiling a document that uses PythonTeX actually executes Python (and potentially other programs) on your machine. You should therefore compile only documents from sources you trust. As an inherent property of anything that “executes” code, this is the same caveat that applies to other approaches relying on --shell-escape.