[英]Python utility fails to successfully run a non-Python script that uses relative paths
我的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/another.tex
编写的输入。
因此,只要与用户选择的/afullpath/a/b/c/mytemplate.tex
处于完全相同的路径,Python实用程序就可以正常工作。 否则pdflatex
找不到自己的输入文件。 pdflatex
发出错误消息,如: ! LaTeX Error: File ./d/another.tex not found
! LaTeX Error: File ./d/another.tex not found
因为执行路径是相对于Python脚本而不是pdflatex
脚本。
[ pdflatex
需要使用相对路径,因为带有.tex文件的文件夹会根据需要移动。
我在堆栈溢出中发现了以下类似情况,但我认为答案不适合这种情况: Python中的相对路径-堆栈溢出
通过引用具有相对路径的其他文件(如./d/another.tex
,您的mytemplate.tex
文件假设(并要求) pdflatex
仅在mytemplate.tex
所在的同一目录上运行。通过在调用os.system
之前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
参数作为乳胶脚本的目录。
见subprocess.run
这里文档,并期待在cwd
的参数subprocess.Popen
。
例:
subprocess.run(["pdflatex", "/afullpath/a/b/c/mytemplate.tex"], cwd="/afullpath/a/b/c/")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.