【问题标题】:pdflatex in a python subprocess on macmac上的python子进程中的pdflatex
【发布时间】:2011-05-12 23:15:30
【问题描述】:

我正在尝试在 Python 2.4.4 的 .tex 文件上运行 pdflatex。子进程(在 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)

【问题讨论】:

    标签: python macos subprocess pdflatex


    【解决方案1】:

    使用便捷功能,subprocess.call

    你不需要在这里使用Popencall 就足够了。

    例如:

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

    【讨论】:

    • 注意:shell=False 是默认值(不需要显式传递)
    • 很棒的帖子。几个月来它帮了我很多,但现在我有一个新问题,我无法指定输出目录,关于如何做的任何线索? tex.stackexchange.com/questions/468278/…
    【解决方案2】:

    您可能想要:

    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撕下来)。

    【讨论】:

    • 对于 1)我认为我需要 stdout=subprocess.PIPE,但它仍然给出错误“OSError:[Errno 2] No such file or directory”,尽管存在并且它在终端中工作.对于 2),尽管设置了 sts,但我运行它时什么也没有发生。
    • 所以它抱怨它找不到“pdflatex”。也许它是外壳中的别名。也许您可以尝试 pdflatex 的完整路径。
    • 宾果游戏,给出完整路径有效,即使它是 pdftex 的别名。虽然这解决了我的问题,但我更喜欢 sukhbir 的语法。感谢您的帮助。
    • 在 Python 3.5+ 上,使用 subprocess.run(["pdflatex", "fullpathtotexfile.tex"], stdout=subprocess.PIPE)
    猜你喜欢
    • 1970-01-01
    • 2014-01-05
    • 2022-10-18
    • 2016-11-09
    • 2012-01-13
    • 2013-07-21
    • 2012-12-26
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多