Run commands sequential from Python
<p>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.</p>

<pre><code>pdflatex file
bibtex file
pdflatex file
pdflatex file
</code></pre>

<p>In Python, I'm therefore doing this to define the commands</p>

<pre><code>commands = ['pdflatex','bibtex','pdflatex','pdflatex']
commands = [(element + ' ' + src_file) for element in commands]
</code></pre>

<p>but the problem is then running them.  </p>

<p>I've tried to suss things out from <a href="http://stackoverflow.com/questions/359347/execute-commands-sequentially-in-python">this thread</a> &ndash; e.g. using <code>os.system()</code> in a loop, <code>subprocess</code> stuff like <code>map(call, commands)</code> or <code>Popen</code>, and collapsing the list to a single string separated by <code>&amp;</code> &ndash; but  it seems like the commands all run as separate processes, without waiting for the previous one to complete.  </p>

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

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

<p>test.py</p>

<pre><code>import subprocess

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

for command in commands:
    subprocess.call((command, 'test'))
</code></pre>

<p>test.tex</p>

<pre><code>\documentclass{article}
\usepackage{natbib}

\begin{document}
This is a test \citep{Body2000}.
\bibliographystyle{plainnat}
\bibliography{refs}
\end{document}
</code></pre>

<p>refs.bib</p>

<pre><code>@book{Body2000,
  author={N.E. Body},
  title={Introductory Widgets},
  publisher={Widgets International},
  year={2000}
}
</code></pre>
