[Tex/LaTex] Unable to use python.sty package

kilelinuxpythonscriptswindows

When compiling a .tex file that uses python.sty package and contains:

\begin{python}
    ...
\end{python}

I keep getting an error:

./main.tex:33:I can't find file 'bin/main.py.out' \end{python}

./main.tex:33:Emergency stop \end{python}

This happens both when compiling with PDFLaTeX or only LaTeX. What I tried is:

  • ensure -shell-enable is on (or -enable-write18 on Windows),
  • find another copy of python.sty in case my version was invalid,
  • try on Windows 7 and on Debian 6 with Kile
  • copy & paste latex samples using python.sty from the web

None of the above helps in getting rid of that error. It fails even with extremely simple python code within the python environment like: print "a". If also fails when I leave the environment contents empty, but with a different error. It doesn't fail if there are no python environments in the document and there is only \usepackage{python} at the top. My python.sty copy is taken from here. Simple example code I tried to compile is there as well.

What am I missing?

Best Answer

Below is definition of python environment inspired by python.sty package, but rewritten to work on my Windows system. Basically, it takes content from between \begin{python} and \end{python}, writes it to a file, executes the file as python script and inserts output into the LaTeX document. Full code:

\usepackage{verbatim}

\makeatletter
\newwrite\Code@out

\newcommand\python{\obeylines\expandafter\pythonArg\noexpand}

\newcommand\pythonArg[1][tmp.py.in]{%
    \gdef\FNameIn{#1}
    \gdef\FNameOut{tmp.py.out}
    \begingroup
        \@bsphack%
        \immediate\openout\Code@out\FNameIn%
        \let\do\@makeother\dospecials%
        \catcode`\^^M\active%
        \def\verbatim@processline{%
            \immediate\write\Code@out{\the\verbatim@line}}%
        \verbatim@start}

\def\endpython{%
        \immediate\closeout\Code@out\@esphack
    \endgroup

     %Execute python script. Python directory must be in PATH.
     \immediate\write18{python \FNameIn > \FNameOut}
     \input{\FNameOut}
}

\makeatother