home
PDF

## A very simple introduction to using Python in Latex

August 4, 2015 page compiled on August 4, 2015 at 11:54pm

This note describes all the steps to use Python inside Latex. The directions are based on using Linux, since this is the system I tried this on.

Using texlive 2014, this package (pythontex) is already there. There is not additional installation needed. Once you install texlive itself, then you have this package.

Here is the most simple tex ﬁle that uses python

\documentclass[11pt]{article}%
\usepackage{pythontex}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}
This document uses Python
\end{document}

Now comes the tricky part. To compile it, we have to do the following commands

pdflatex foo.tex
/usr/local/texlive/2014/texmf-dist/scripts/pythontex/pythontex.py  foo.tex
pdflatex foo.tex

We have to run the above 3 commands each time. On my installation of texlive 2014, the script pythontex.py was not already in the path, so instead of keep typing the above long command each time, I added an alias to my bashrc

vi $HOME/.bashrc #add this line below to the file alias PYX=/usr/local/texlive/2014/texmf-dist/scripts/pythontex/pythontex.py #after exiting vi, typed source$HOME/.bashrc

So now I can write (less typing) the following

pdflatex foo.tex
PYX  foo.tex
pdflatex foo.tex

Or you can add it to the path. You must have python itself installed. Version 2.7 or better, else none of the above will work.

In the above example, we did not do anything interesting. Lets now make a python variable, multiply it by 2, and show the result in Latex

\documentclass[11pt]{article}%
\usepackage{pythontex}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}
\begin{pyconsole}
x = 987.27
x = x**2
\end{pyconsole}

The variable is $x=\pycon{x}$
\end{document}

Which produces the following when the document is compiled

\begin{pyconsole}
x = 987.27
x = x**2
\end{pyconsole}

References:

1.
Pythontex main documenation http://www.ctan.org/pkg/pythontex
2.
pythontex quickstart PDF
3.
Pythontex GitHub
4.
A Gentle Introduction to PythonTeX