首页 > 解决方案 > pyinstaller 阻止 python 从脚本目录读取

问题描述

我有这个以 python 脚本形式工作的代码块,但是当我使用 pyinstaller 将脚本打包到 exe 时,它​​总是导致程序说找不到配置文件。我把它放在config.ini与exe文件相同的文件夹中。

config = configparser.ConfigParser()
configComplete = True
configExists = False
try:
    open(os.path.join(sys.path[0],'config.ini'))
    config.read(os.path.join(sys.path[0],'config.ini'))
    destination = config['server']['ServerAddress']
    key = config['server']['ApiKey']
    configExists = True
except KeyError:
    configComplete = False
except FileNotFoundError:
    try:
        open(expanduser('~/.config/octoprint-cli.ini'))
        config.read(expanduser('~/.config/octoprint-cli.ini'))
        destination = config['server']['ServerAddress']
        key = config['server']['ApiKey']
        configExists = True
    except KeyError:
        configComplete = False
    except FileNotFoundError:
        pass

标签: python-3.xpyinstallerconfigparser

解决方案


我目前没有安装 python 来在我的机器上测试它,但通常当我在寻找与 python 文件位置相关的文件时,最好使用:

import os

CONFIG_FILE_PATH = f"{os.path.dirname(__file__)}{os.sep}config.ini"


if os.path.exists(CONFIG_FILE_PATH): # If the file already exists
    config.read(CONFIG_FILE_PATH) # Read it

else: # If a config file does not exist
    # Either throw error or create fresh config

此代码是一种与操作系统无关的方式,用于在与 python 文件相同的目录中查找文件,除非您愿意,否则捕获不一定会引发错误。

看看这是否适用于 pyinstaller,因为我相信当我上次使用它时它有效。


推荐阅读