繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM