我正在尝试从Python 2.4.4在.tex文件上运行pdflatex。 subprocess(在mac上):
import subprocess
subprocess.Popen(["pdflatex", "fullpathtotexfile"], shell=True)
实际上什么也没做。但是,我可以在终端中运行“pdflatex fullpathtotexfile”而不会出现问题,生成pdf。我错过了什么?
[编辑] 正如其中一个答案所示,我试过了:
return_value = subprocess.call(['pdflatex', '/Users/Benjamin/Desktop/directory/ON.tex'], shell =False)
失败了:
Traceback (most recent call last):
File "/Users/Benjamin/Desktop/directory/generate_tex_files_v3.py", line 285, in -toplevel-
return_value = subprocess.call(['pdflatex', '/Users/Benjamin/Desktop/directory/ON.tex'], shell =False)
File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/subprocess.py", line 413, in call
return Popen(*args, **kwargs).wait()
File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/subprocess.py", line 543, in __init__
errread, errwrite)
File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/subprocess.py", line 975, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
该文件确实存在,我可以在终端中运行pdflatex /Users/Benjamin/Desktop/directory/ON.tex
。请注意,pdflatex会发出大量警告......但这不重要,这也会产生同样的错误:
return_value = subprocess.call(['pdflatex', '-interaction=batchmode', '/Users/Benjamin/Desktop/directory/ON.tex'], shell =False)
答案 0 :(得分:4)
使用便利功能subprocess.call
您无需在此使用Popen
,call
就足够了。
例如:
>>> import subprocess
>>> return_value = subprocess.call(['pdflatex', 'textfile'], shell=False) # shell should be set to False
如果通话成功,return_value
将设置为0,否则为1.
Popen
的使用通常适用于您希望存储输出的情况。例如,您想使用命令uname
检查内核版本并将其存储在某个变量中:
>>> process = subprocess.Popen(['uname', '-r'], shell=False, stdout=subprocess.PIPE)
>>> output = process.communicate()[0]
>>> output
'2.6.35-22-generic\n'
同样,永远不要设置shell=True
。
答案 1 :(得分:1)
你可能想要:
output = Popen(["pdflatex", "fullpathtotexfile"], stdout=PIPE).communicate()[0]
print output
或
p = subprocess.Popen(["pdflatex" + " fullpathtotexfile"], shell=True)
sts = os.waitpid(p.pid, 0)[1]
(从这subprocess doc page section无耻地撕掉)。