Python Mac OS X 不在外部 XML 文件中加载,当它是应用程序时
Python Mac OS X not loading in external XML file when it is an app
我有一个 Python3 脚本加载文件 parameters/parameters.xml。该脚本内置于带有 PyInstaller 的应用程序中。通过以下方式启动,脚本和应用程序运行正常:
- Windows 命令行
- Windows 在资源管理器中双击
- Mac OS X 命令行
从 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
:因为脚本使用相对于当前工作目录的路径,所以应该首先设置当前目录。
我有一个 Python3 脚本加载文件 parameters/parameters.xml。该脚本内置于带有 PyInstaller 的应用程序中。通过以下方式启动,脚本和应用程序运行正常:
- Windows 命令行
- Windows 在资源管理器中双击
- Mac OS X 命令行
从 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
:因为脚本使用相对于当前工作目录的路径,所以应该首先设置当前目录。