gpt4 book ai didi

当 Python Mac OS X 是应用程序时,不会加载外部 XML 文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:34 25 4
gpt4 key购买 nike

我有一个加载文件parameters/parameters.xml的Python3脚本。该脚本通过 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的需要:由于脚本使用相对于当前工作目录的路径,因此应该首先设置当前目录。

关于当 Python Mac OS X 是应用程序时,不会加载外部 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com