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

Python实用程序无法成功运行使用相对路径的非Python脚本,python,python-3.x,relative-path,absolute-path,os.system,Python,Python 3.x,Relative Path,Absolute Path,Os.system,我的Python3实用程序有一个无法工作的函数(除非它被放置在选定的目录中,然后它可以在该目录中成功运行非pythonpdflatex脚本)。我想在我拥有的任何template.tex文件上的一个设置位置运行该实用程序,该文件存储在各种其他位置 Python实用程序提示用户使用tkinter.filedialog GUI从绝对路径选择pdflatex模板文件,然后运行用户选择的pdflatex脚本,例如使用:os.system(“pdflatex/afullpath/a/b/c/mytempla

我的Python3实用程序有一个无法工作的函数(除非它被放置在选定的目录中,然后它可以在该目录中成功运行非python
pdflatex
脚本)。我想在我拥有的任何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/other.tex

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

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


我在堆栈溢出上发现了以下类似的情况,但我认为答案并不针对这种情况:

通过引用具有相对路径的其他文件,如
/d/other.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))

通过引用具有相对路径(如
/d/other.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.Popen
cwd
参数

例如:

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

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

请参阅此处的文档,并查看
subprocess.Popen
cwd
参数

例如:

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

我不认为更改Python自己的工作目录是个好主意,我不认为更改Python自己的工作目录是个好主意。