Python Mac OS X作为应用程序时不加载外部XML文件
我有一个加载文件parameters/parameters.xml的Python3脚本。该脚本内置于带有PyInstaller的应用程序中。通过以下方式启动,脚本和应用程序工作正常:Python Mac OS X作为应用程序时不加载外部XML文件,python,macos,pyinstaller,Python,Macos,Pyinstaller,我有一个加载文件parameters/parameters.xml的Python3脚本。该脚本内置于带有PyInstaller的应用程序中。通过以下方式启动,脚本和应用程序工作正常: -Windows命令行 -Windows在资源管理器中双击 -MacOSX命令行 从OS X Finder启动应用程序时,无法找到XML文件 调用该文件的代码被截断: try: self.paramTree = ET.parse("../parameters/parameters.xml") except:
-Windows命令行
-Windows在资源管理器中双击
-MacOSX命令行 从OS X Finder启动应用程序时,无法找到XML文件 调用该文件的代码被截断:
try:
self.paramTree = ET.parse("../parameters/parameters.xml")
except:
self.paramTree = ET.parse("parameters/parameters.xml")
self.paramRoot = self.paramTree.getroot()
如何使文件始终从应用程序的位置加载?您可以通过相对路径访问文件。看起来当前工作目录的设置方式与上一个案例(OS X Finder)中的设置方式不同:这将导致找不到文件 因此,您可以根据程序的位置设置工作目录:
import os
# __file__ is a relative path to the program file (relative to the current
# working directory of the Python interpreter).
# Therefore, dirname() can yield an empty string,
# hence the need for os.path.abspath before os.chdir() is used:
prog_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(prog_dir) # Sets the current directory
您可以将当前工作目录设置为与此稍有不同的内容,具体取决于脚本所需的内容(可能是脚本的父目录:os.path.join(prog_dir,os.pardir)
)
这甚至可以消除执行try
:由于脚本使用相对于当前工作目录的路径,因此应该首先设置当前目录。文件只是在python 3中给出了文件名,通过添加函数os.path对其进行了修复。abspathabspath()
确实应该使用(我修复了答案)。但是,\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
确实给出了程序的路径(而不是名称),相对于当前工作目录(。参考:,“模块”一节。