Running pythontex from TeX using \immediate\write18 fails, for reasons that are unclear to me. See my example file below.


pdflatex -shell-escape p.tex

does not produce the pycode.txt file as desired. However, running

pythontex p.tex

does. The logs don't give any obvious indication of failure.

%%%%%%%%%%%%% p.tex %%%%%%%%%%%%%%%
f = open("pycode.txt", 'w')
f.write("Hello, this is Python writing from TeX.")
\immediate\write18{pythontex \jobname.tex}

pythontex writes code and related information to a tempfile .pytxcode, which is then used to execute the code later. This tempfile is opened as soon as pythontex is loaded, and is closed \AfterEndDocument. If you try to run pythontex in the preamble, it will read an incomplete tempfile, and as a result give an error about the tempfile format.

What you want to do is run pythontex after the tempfile is completed and closed. Using \AfterEndDocument{\immediate\write18{pythontex \jobname.tex}} works for me. Another option would be to run the \write18 command before loading pythontex, perhaps with a conditional to detect the presence of the tempfile.

  • Thanks very much. That works. But I didn't notice any error about the tempfile format. "perhaps with a conditional to detect the presence of the tempfile." Why is that necessary? – Faheem Mitha Oct 19 '15 at 13:05
  • @FaheemMitha Recent versions of pythontex should give a message like "The .pytxcode file appears to have an outdated format or be invalid". A conditional could be useful on the first compile, when the tempfile doesn't exist; in that case, there's no need to run pythontex, though doing so won't cause problems (pythontex will just exit with an error). – G. Poore Oct 19 '15 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.