Recently, while browsing the archives of the matplotlib mailing list, I stumbled upon the small python.sty package written by Martin R. Ehmsen. The package allows you to embed Python code in your document. When the document is compiled the code will be automatically run and its output included in the document. I’m a big fan of the Python programming language, so naturally I wanted to try it out.

How it works

Let’s start with a basic “hello world” example:

%& -shell-escape
\documentclass{article}
\usepackage{python}
\begin{document}

Say hello Python:

\begin{python}%
print r"Hello \LaTeX!"
\end{python}%
\end{document}

Compiling the above code with shell escape enabled gives the following output:

Hello world!

Not very spectacular, but the example shows how the package works:

  1. The code inside the \begin{python}...\end{python} environment is run through the python interpreter.
  2. Everything that is written to standard output(stdout) is saved to a temporary file and included in the document.
  3. The output from the Python program is interpreted as ordinary LaTeX code.

Something more advanced

Her is a more interesting example:

%& -shell-escape
\documentclass{article}
\usepackage{graphicx}
\usepackage{python}
\begin{document}

\begin{figure}
\centering
\begin{python}
#
from pyx import *

g = graph.graphxy(width=8)
g.plot(graph.data.function("y(x)=sin(x)/x", min=-15, max=15))
g.writePDFfile("function")
print r'\includegraphics{function}'
\end{python}
\caption{$y(x)=\frac{\sin(x)}{x}$}
\end{figure}

\end{document}

The above script loads PyX, an excellent Python graphics package, plots a function, saves the plot as a PDF and includes it using \includegraphics:

Hello world!

Summary

The python.sty package is useful as is, but the current version has a few issues:

  • Every python environment use the same temporary files. This means that when you compile document with multiple python environments without shell escape enabled, the output from the last script will be used for all the python environments.
  • The cat command line tool is used when invoking python. The tool is standard on all *nix-like systems, but not on Windows. Windows users can find cat and many other useful tools in the UnxUtils bundle.

The above issues should not be difficult to fix. Experimenting with the python.sty package is fun and it is a useful tool to have in your LaTeX toolbox.

Update: Apparently I’m not the only one that have written about python.sty:

All of the above posts contains examples.

Comments

  • #1 Ken Starks, October 24, 2008 at 1:29 p.m.

    Thanks for sharing this Kjell. I have been running PyX and PGF/TikZ in parallel as I build up my skills in each, and this means I can more easily use them together.

    For others: The two examples provided did not work un an unmodified version of TexnicCentre, but went through with no trouble when compiled using the command line.

    Thanks again.

    Ken

  • #2 Kjell Magne Fauske, October 24, 2008 at 1:54 p.m.

    @Ken Starks. You need to enable shell escape in TexnicCenter, either by adding the command line option to the output profile configuration, or by letting the following line be the first line of your document :

    %& -shell-escape
    

    If there are any spaces or newlines before the above line it will not work.

  • #3 Sudchai Boonto, October 28, 2008 at 5:20 p.m.

    How you can use this line in windows ?

    \immediate\write18{cat \@pythoninclude\space\jobname.py | python > \jobname.py.out 2> \jobname.py.err}
    

    For me, I simply use

    \immediate\write18{python \jobname.py \jobname.py.out 2>\jobname.py.err}
    

    Thank for wonderful thing.

  • #4 Kjell Magne Fauske, October 29, 2008 at 9:27 a.m.

    @Sudchai Thanks for the tip! It is really as simple as that.

    Another modification is to add a counter variable so that the code output from each environment is put in a separate file. This allows you to run the file without shell escape enabled. Here is a quick hack:

    ...
    \newcounter{py@codenum}
    \def\@python[#1]{%
    \stepcounter{py@codenum}
    \gdef\@pythoninclude{#1}
    \immediate\openout\@out=\jobname.py
    \newlinechar='15
    \begingroup \catcode`\^^M=12 %
    \let\do\@makeother\dospecials\obeyspaces%
    \@xpython}
    
    \def\endpython{%
    \endgroup
    \immediate\closeout\@out
    \@writemodule
    \immediate\write18{python\space\jobname.py > \jobname.py.\thepy@codenum.out 2> \jobname.py.\thepy@codenum.err}
    \immediate\input\jobname.py.\thepy@codenum.out}
    ...
    
  • #5 Kjell Magne Fauske, November 3, 2008 at 11:44 a.m.

    Updated post with links to other people that have written about python.sty.

  • #6 kib2, November 5, 2008 at 2:54 p.m.

    Hi Kjell,

    thanks for the references.

    I'm reading your (really nice) blog posts with interest in both Python and LaTeX.

    Do you think it's possible to create a PGF backend in Python ? Sure you won't have a total PGF backend, but it may be a good option for simple figs.

    I've started something like this (some images are still here : http://picasaweb.google.fr/kibleur.christophe/PGF#) some time ago and since, I let it down, because I've found no way on how to compute "whatever" intersections between 2 paths.

    If you have any idea or interest on such a module, please tell me.

    Cheers,

    Kib².

  • #7 Kjell Magne Fauske, November 5, 2008 at 3:24 p.m.

    @kib2. Interesting ideas. Thanks for sharing.

    Do you think it's possible to create a PGF backend in Python ? Sure you won't have a total PGF backend, but it may be a good option for simple figs.

    I assume you mean a Python module that can generate PGF/TikZ code for you? It sure is possible. I have thought along those lines myself while working on my various xx2tikz converters.

    A good place to start is probably PyX. It looks well designed and offers a nice API for manipulating paths. I have only briefly looked at its source code, but it should be possible to create a PGF backend for it. It already supports PDF and EPS. If it is difficult you can at least use PyX's path manipulation algorithms.

    Matplotlib is another project that could use a PGF/TikZ backend ...

    I've started something like this (some images are still here : http://picasaweb.google.fr/kibleur.christophe/PGF#) some time ago and since, I let it down, because I've found no way on how to compute "whatever" intersections between 2 paths.

    You are probably aware of it, but arbitrary intersections are available in PGF CVS. Your (abandoned) project looks very interesting.

  • #8 kib2, November 5, 2008 at 3:34 p.m.

    Matplotlib,

    Yes I'm aware of this fact, but I really don't like the PGF syntax (nor the PSTricks or the Asymptote one).

    I've started the project just to type a figure in a more natural langage where you can write your own functions, methods or objects more easily ( GeoPyX was my first attempt, but I was just starting with Python at the time, I don't use it anymore because PyX does not works actually on my windows machine).

  • #9 Kjell Magne Fauske, November 5, 2008 at 8:02 p.m.

    Thanks for sharing kib. GeoPyX really looks like a good start. Reminds me of GeoGebra. You probably know much more about PyX than I do. Creating a PGF backend for it is probably harder than it looks like.

    PyX does work on windows if you install it manually without using the setup.py file. If you copy the contents of the pyx folder to your python path it should work.

  • #10 kib2, November 5, 2008 at 11:47 p.m.

    Thanks Kjell, I'll try your solution.

    Have you tried the latest Geogebra version with Tikz export : really nice ? (I suppose you're maybe the one how made it, but I may be wrong).

    Cheers.

  • #11 Kjell Magne Fauske, November 6, 2008 at 7:52 a.m.

    I have tried the Geogebra TikZ exporter. It is very well done. I have had nothing to do with the development of the exporter. I don't know the full name of the author. In the GeoGebra user forum he uses the nickname loiclecoq.

  • #12 curiouslearn, December 8, 2008 at 11:21 p.m.

    Unfortunately, the above code does not work for me. I entered the line %& -shell-escape in my document and it was the first line as Kjell suggested. I am using textmate in Mac OSx. The Tex distribution is BasicTex. Could any of these be the problem?

    Thanks.

  • #13 Kjell Magne Fauske, December 9, 2008 at 7:56 a.m.

    @curiouslearn It is probably a problem with your TeX distribution. I'm not familiar with the one you mention. It could be that it uses a different option for enabling shell escape. Have you tried running the example from the command line?

  • #14 curiouslearn, December 13, 2008 at 5:42 p.m.

    Thanks for your reply Kjell. I appreciate it. Yes, I tried running from the command line (terminal) and it works very well from there.

    I used the following command at the terminal line:

    pdflatex -shell-escape filename.tex

  • #15 Schremmer, December 29, 2008 at 10:55 p.m.

    I was much intrigued by the sin(x)/x example:

    I am engaged in a rather big project (See freemathtexts.org) so have little time learning new stuff. Learning gnuplot_tikz-pgf seems to be more than I have time for and an overkill for what I need—even though I find the examples fascinating.

    Still, I am soon going to need including lots of graphs of functions in LaTeX with TeXShop under OS X 10.4.11 and using python.sty would seem to be about what I need but I know nothing about python.

    And then of course, there is sagetex (third ref.) which looks even more useful for the question banks.

    Question: Could you recommend a manual to learn just what I would need? (Please keep in mind that I am terminally allergic to the terminal. For instance, I have no idea what "shell enabled" means.)

    Hopeful regards --schremmer

  • #16 Kjell Magne Fauske, December 30, 2008 at 2:07 p.m.

    @Schremmer. You could probably use python.sty to generate the plots, but you then will need to learn Python and one of the available plotting packages. In the above post I have mentioned PyX. Matplotlib is another candidate.

    I have not tried the sagetex package, but after browsing the documentation I would in your case recommend using sagetex instead of python.sty. Sage is Python based, but I don't think you need to learn Python for creating basic plots. I have not tried Sage yet, but you will probably find everything you need to get started on the projects help page.

  • #17 Sean McDevitt, February 9, 2009 at 5:53 a.m.

    I'm interested in using this package to generate automatic forms with plots. I take data from various devices, and create a report in a standard template. This latex option has spiked my interest.

    However, when I call pdflatex from within a python shell using subprocess.Popen("pdflatex.exe"... I cannot get the python generated output to be created. In short, the pdf has all the text desired EXCEPT for the text/plots generated by python. Any ideas?

    Does anyone have a better implementation?

  • #18 Kjell Magne Fauske, February 9, 2009 at 8:25 a.m.

    @Sean. Are you using python.sty to to run a script that again runs pdflatex internally? This should work, but what are you doing with the output from pdflatex? Have you remembered to include the generated pdf in the outer document?

  • #19 Zaynebx Morringi, May 20, 2012 at 6:43 p.m.

    This is my first time pay a visit at here and i am genuinely pleassant to read everthing at alone place.

Adding comments is currently not enabled.