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