Python 实用程序无法成功 运行 使用相对路径的非 Python 脚本

Python utility fails to successfully run a non-Python script that uses relative paths

我的 Python3 实用程序有一个功能不起作用(除非它被放置在 selected 目录中,然后它可以 运行 非 python pdflatex 脚本成功)。我想从我拥有的任何 template.tex 文件的设置位置 运行 实用程序,这些文件存储在其他不同位置。

Python 实用程序提示用户使用 tkinter.filedialog GUI 从绝对路径 select 一个 pdflatex 模板文件,然后 运行s用户的 selected pdflatex 脚本使用,例如:os.system("pdflatex /afullpath/a/b/c/mytemplate.tex")

Python 的 os.system 运行 的 pdflatex,然后 运行 的 mytemplate.tex 脚本。 mytemplate.tex 有许多输入用相对路径编写,例如 ./d/another.tex.

因此,只要 Python 实用程序与用户 select 位于与 /afullpath/a/b/c/mytemplate.tex 完全相同的路径中,它就可以正常工作。否则 pdflatex 无法找到自己的输入文件。 pdflatex 传递如下错误消息:! LaTeX Error: File ./d/another.tex not found 因为执行路径是相对于 Python 脚本而不是 pdflatex 脚本。

[pdflatex 需要使用相对路径,因为包含 .tex 文件的文件夹会根据需要四处移动。]

我在 Stack Overflow 上发现了以下类似案例,但我认为答案不适合这种情况:Relative Paths In Python -- Stack Overflow

通过引用具有 ./d/another.tex 等相对路径的其他文件,您的 mytemplate.tex 文件假设(并要求)pdflatex 只是 运行 来自mytemplate.tex 所在的同一目录。因此,您需要在调用 os.system:

之前切换到包含 mytemplate.tex 的目录来满足此要求
input_file = '/afullpath/a/b/c/mytemplate.tex'
olddir = os.getcwd()
os.chdir(os.path.dirname(input_file))
os.system('pdflatex ' + input_file)
os.chdir(olddir)

更好的方法是使用 subprocess.call,因为它会为您处理目录更改并且不易受到 shell 引用问题的影响:

subprocess.call(['pdflatex', input_file], cwd=os.path.dirname(input_file))

使用subprocess.run代替os.system并传入cwd参数作为latex脚本的目录

请参阅此处的 subprocess.run 文档,并查看 subprocess.Popencwd 参数。

示例:

subprocess.run(["pdflatex", "/afullpath/a/b/c/mytemplate.tex"], cwd="/afullpath/a/b/c/")