Python 如何访问Tkinter exe文件中的模型权重?

Python 如何访问Tkinter exe文件中的模型权重?,python,pyinstaller,exe,Python,Pyinstaller,Exe,我已经生成了一个Tkinter GUI,并生成了一个复制模型权重的exe文件 “权重”文件夹与myTKcode.py文件位于同一文件夹中 我生成的模型和负载权重如下所示: import tensorflow as tf model = MyModel() model.load_weights("weights/MyModelWeights") pyinstaller --onefile --add-data weights;weights myTKcode.py pyin

我已经生成了一个Tkinter GUI,并生成了一个复制模型权重的exe文件

“权重”文件夹与myTKcode.py文件位于同一文件夹中

我生成的模型和负载权重如下所示:

import tensorflow as tf
model = MyModel()
model.load_weights("weights/MyModelWeights")
pyinstaller --onefile --add-data weights;weights myTKcode.py
pyinstaller --onefile --add-data weights;weights myTKcode.py
现在,如果我使用pyinstaller生成一个exe文件,如下所示:

import tensorflow as tf
model = MyModel()
model.load_weights("weights/MyModelWeights")
pyinstaller --onefile --add-data weights;weights myTKcode.py
pyinstaller --onefile --add-data weights;weights myTKcode.py
根据
myTKcode.exe
文件的大小,我可以说在
myTKcode.exe
中添加了权重。但是当我运行
myTKcode.exe
文件时,它找不到权重文件夹。但是,如果我将权重文件夹复制粘贴到
dist
文件夹中
myTKcode.exe
所在的位置,它就会工作


我的问题是如何访问存储在
myTKcode.exe
中的权重?

以前曾问过类似的问题并找到了解决方案

简而言之,对于每个文件夹/文件,必须将绝对路径添加到独立的exe文件中

因为我有一个名为weights的文件夹;我只需将以下代码添加到我的代码中:

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)
然后我加载重量如下

import tensorflow as tf
model = MyModel()
#model.load_weights("weights/MyModelWeights")
weightDir = resource_path("weights") # resource_path get the correct path for weights directory.
model.load_weights(weightDir+"/MyModelWeights")
然后只需运行
pyinstaller
,如下所示:

import tensorflow as tf
model = MyModel()
model.load_weights("weights/MyModelWeights")
pyinstaller --onefile --add-data weights;weights myTKcode.py
pyinstaller --onefile --add-data weights;weights myTKcode.py

始终使用绝对路径而不是相对路径。您可能需要一个环境变量或一个命令行参数来指定“工作”目录。我知道这是一个糟糕的想法,但从理论上讲,您不能在程序中对权重进行base64编码和硬编码吗?之后,您可以在运行时在临时文件夹中展开它们?