【问题标题】:Python Mac OS X not loading in external XML file when it is an appPython Mac OS X 在作为应用程序时未加载到外部 XML 文件中
【发布时间】:2016-11-11 08:48:03
【问题描述】:

我有一个加载文件 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()

我怎样才能使文件始终从应用程序的位置加载?

【问题讨论】:

    标签: python macos pyinstaller


    【解决方案1】:

    您通过相对路径访问文件。看起来当前工作目录的设置方式与上一种情况(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:因为脚本使用相对于当前工作目录的路径,所以应该首先设置当前目录。

    【讨论】:

    • file 只是给出了 python 3 中的文件名,通过添加函数 os.path.abspath 来修复它
    • abspath() 确实应该使用(我修复了答案)。然而,__file__ 确实给出了程序的路径(不是程序的名称),相对于当前工作目录(这就是为什么在某些情况下人们可能认为它只给出程序文件名)。参考:docs.python.org/2/reference/…,“模块”部分。
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2013-01-19
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多