我有此代码块以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,正如我上次使用时所相信的那样。