从Python顺序运行命令

0 投票
1 回答
4458 浏览
提问于 2025-04-17 01:54

我正在尝试用Python创建一个LaTeX文档,但在让命令按顺序运行时遇到了问题。对于熟悉LaTeX的人来说,你们知道通常需要运行四个命令,每个命令在下一个命令运行之前都要完成,比如:

pdflatex file
bibtex file
pdflatex file
pdflatex file

在Python中,我是这样定义这些命令的:

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

但问题在于如何运行它们。

我试着从这个讨论串中找出解决办法,比如在循环中使用os.system(),或者用subprocess的东西,比如map(call, commands)Popen,还有把命令列表合并成一个用&分隔的字符串,但似乎这些命令都是作为独立的进程运行的,没有等前一个完成就开始下一个。

顺便说一下,我是在Windows上,但我希望有一个跨平台的解决方案。

编辑
问题出在指定src_file变量时的一个错误;它不应该有“.tex”。以下代码现在可以正常工作:

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}
}

1 个回答

4

os.system 这个方法不应该引起这个问题,但 subprocess.Popen 可能会。

不过我觉得使用 subprocess.call 是最好的选择:

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

for command in commands:
    subprocess.call((command, src_file)) 

撰写回答