Posts

Showing posts from November, 2013

Running Python code in a LaTeX document

Image
I am currently working on a LaTeX document in which the content is still in a very fluid phase and  the figures change often. I usually have a Python script that prepares the figures and saves them as PDFs. To iterate faster, I wanted to insert Python code directly into LaTeX, executing the code when the document is compiled.

Googling around I found that I was not the first one to want this. There is this LaTeX package with this github repo. The package provides a new environment (python) within which you can write arbitrary Python code. The code is executed when the document is compiled and the output is inserted into the document.

I try it and it worked like a charm. It was even printing the traceback in red when there was an error in the script. You can do things like this:

\documentclass[a4paper]{book} \usepackage[pdftex]{graphicx} \usepackage{python} \begin{document} A simple example: \begin{python} print(2+3) \end{python} \vspace{1cm} Generating and displaying a figure: \be…