开发者

Run commands sequential from Python

开发者 https://www.devze.com 2023-04-04 00:35 出处:网络
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

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 t开发者_StackOverflow社区o 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}
}


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)) 
0

精彩评论

暂无评论...
验证码 换一张
取 消