python-3.x - 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 来在我的机器上测试它,但通常当我在寻找与 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,因为我相信当我上次使用它时它有效。
推荐阅读
- hyperledger-indy - libindy 中创建凭证提案的方法是什么?
- android - 如何在 Android 上为视图实现卷曲或波浪形边框?
- javascript - 承诺中的 Twilio 方法不起作用
- javascript - 如何在 Nuxt.js 中使用经过身份验证的 websocket?
- typescript - 使用 Typescript 解构对象
- ios - Windows 上的 Unity iOS 构建日志
- c - 从文件转换 HEX ASCII 字符串并创建二进制文件
- c++ - 我打开了代码、内存和手表。我如何理解这些十六进制值?
- python - Python TypeError:尝试打印时无法连接“str”和“int”对象
- angular - 不能在子组件中更改按钮状态