Python实用工具无法成功运行使用相对路径的nonPython脚本

2024-05-19 10:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python3实用程序有一个不起作用的函数(除非它放在选定的目录中,然后它就可以成功地运行非pythonpdflatex脚本)。我想在任何template.tex文件上的一个设置位置运行该实用程序,该文件存储在其他不同的位置

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

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

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

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

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


Tags: 文件函数用户路径实用程序脚本osanother
2条回答

通过引用其他具有相对路径(如./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)

更好的方法是使用^{},因为它可以为您处理目录的更改,并且不易受到shell引用问题的影响:

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

使用subprocess.run而不是os.system,并传入cwd参数作为latex脚本的目录

在这里查看^{}文档,并查看subprocess.Popencwd参数

示例:

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

相关问题 更多 >

    热门问题