簡體   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