0

I'm trying to build a LaTeX document using Python but am having problems getting the commands to run in sequence. For those familiar with LaTeX, you'll know that you usually have to run four commands, each completing before running the next, e.g.

pdflatex file
bibtex file
pdflatex file
pdflatex file

In Python, I'm therefore doing this to define the commands

commands = ['pdflatex','bibtex','pdflatex','pdflatex']
commands = [(element + ' ' + src_file) for element in commands]

but the problem is then running them.

I've tried to suss things out from this thread – e.g. using os.system() in a loop, subprocess stuff like map(call, commands) or Popen, and collapsing the list to a single string separated by & – but it seems like the commands all run as separate processes, without waiting for the previous one to complete.

For the record, I'm on Windows but would like a cross-platform solution.

EDIT
The problem was a bug in speciyfing the src_file variable; it's shouldn't have a ".tex". The following code now works:

test.py

import subprocess

commands = ['pdflatex','bibtex','pdflatex','pdflatex']

for command in commands:
    subprocess.call((command, 'test'))

test.tex

\documentclass{article}
\usepackage{natbib}

\begin{document}
This is a test \citep{Body2000}.
\bibliographystyle{plainnat}
\bibliography{refs}
\end{document}

refs.bib

@book{Body2000,
  author={N.E. Body},
  title={Introductory Widgets},
  publisher={Widgets International},
  year={2000}
}
3
  • 1
    If you use the accepted answer from that thread that uses Popen.wait(), that should work. Commented Sep 9, 2011 at 17:46
  • I thought that looked promising but to be honest, I don't really follow the code example. 2 classes seems like a lot of code for a simple task. Commented Sep 9, 2011 at 17:53
  • The answer from utdemir is simpler. but call is pretty much equivalent to Popen(...) then calling wait() on the returned object. Commented Sep 9, 2011 at 17:56

1 Answer 1

4

os.system shouldn't cause this, but subprocess.Popen should.

But I think using subprocess.call is the best choice:

commands = ['pdflatex','bibtex','pdflatex','pdflatex']

for command in commands:
    subprocess.call((command, src_file)) 
Sign up to request clarification or add additional context in comments.

2 Comments

Nope - that doesn't run them sequentially. The LaTeX document still has missing cross-references. (I've checked the source files with a manual build.)
Right you are! Having the tex extension on the src_file string breaks the bibtex compilation. I've added the change above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.