Python inside LaTeX (and Sage too)

I discovered recently, that it is possible to run Python scripts from LaTeX documents and use the to generate document's content. This can be used to read/convert data, generate tables and figures, do on-the-fly calculations.

How to run Python code from LaTeX:

  • download python.sty. Put it in the same directory as the LaTeX document
  • \usepackage{python}
  • Put Python code inside \begin{python}\end{python} environment. Whatever this code prints, will become part of the LaTeX document.
  • Run LaTeX with -shell-escape option (this permits running external code from LaTeX)
This is an example of the LaTeX document and the PDF produced.

And some more advanced examples are in this LaTeX file (see also the PDF). They cover symbolic calculations from inside LaTeX, plotting and variable persistence between python environments.

P.S. What's more, one can even embed the full-featured symbolic math package Sage into LaTeX. For this purpose use sagetex package. By the way, you do not need to install Sage to start using it, please check out its web-version. It is really powerful.


This post in Russian: Python внутри LaTeX (и математический пакет Sage тоже)