python - PyInstaller 未捆绑特定文件夹及其内容
问题描述
我一直在尝试使用 PyInstaller 将一个项目捆绑到一个文件中。我已经成功添加了所有必需的二进制文件和其他文件,除了一个文件夹中的文件,我已经尝试过解决其他类似问题的解决方案,但无济于事。我也浏览了文档,但我认为我仍然遗漏了一些东西。我尝试使用相对路径和绝对路径进行添加。我的项目结构如下,
Project_Root_Folder
model(folder)
model.json file
.h5 file
other_data_folders
other.py files
other_binaries
我的规格文件,
import PyInstaller.utils.hooks as hooks
from glob import glob
import os
from PyInstaller.utils.hooks import collect_submodules, collect_data_files
tensorflow_location = '/home/user/miniconda3/envs/project/lib/python3.7/site-packages/tensorflow'
tensorflow_binaries = []
for dir_name, sub_dir_list, fileList in os.walk(tensorflow_location):
for file in fileList:
if file.endswith(".so"):
full_file = dir_name + '/' + file
print(full_file)
tensorflow_binaries.append((full_file, '.'))
def resource_path(relative):
return os.path.join(os.environ.get("_MEIPASS2", os.path.abspath(".")), relative)
block_cipher = None
added_binaries = [('_pytransform.so','.'),('lanms/adaptor.so','.')]
#added_files = collect_data_files('nltk',False)
added_files = [
('pytransform.*','.'),
#('/home/user/nltk_data',"nltk_data"),
('lanms/*','lanms'),
(resource_path('model/*'),'model'),
(resource_path('model/model.json'),'model')
hidden_imports = []+collect_submodules('scipy.ndimage')+collect_submodules('shapely.geometry')
added_binaries = added_binaries + tensorflow_binaries
__file__ = 'run.spec'
cur_dir = os.path.dirname(os.path.abspath(__file__))
a = Analysis(['run.py'],
pathex=[cur_dir,
],
binaries=[('./_pytransform.so','.')]+tensorflow_binaries,
datas=added_files,
hiddenimports=hidden_imports,
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='project',
debug=False,
strip=False,
upx=True,
console=True )
捆绑过程完成并运行二进制文件后,它说它无法找到“model/model.json”。当我将模型文件夹与二进制文件放在同一文件夹中时,项目按预期工作,但我无法将它与其他文件、文件夹和二进制文件捆绑到同一个“一个文件”中。我错过了什么。
解决方案
我弄清楚我做错了什么。我会在这里分享它,以防其他人像我一样陷入愚蠢的困境。在我加载json文件的程序中,我应该使用resource_path函数加载它。我之前在spec文件中使用了resource_path函数。
def resource_path(relative):
return os.path.join(
os.environ.get(
"_MEIPASS2",
os.path.abspath(".")
),
relative
)
json_file = open(resource_path(previously_used_path),'r')
推荐阅读
- mxgraph - mxGraph:当我删除所有单元格时,布局管理器停止工作
- java - 将 AsyncTask 重置为多次执行
- angular - 为什么订阅函数中的代码会执行多次
- html - 当 flex-direction 设置为 column 时,如何使用 flexbox 将元素与 div 的底部对齐
- angular - ngx-translate 刷新页面后切换到默认语言
- django - 为 django 建模 ER 图
- c# - 区域顶点在 Eyeshot 上略有不同
- c# - 是否建议在 Windows 服务中运行 Visual Studio Tools for Office?
- mule - 如何解决 Anypoint studion 7 错误?
- javascript - 反应路由器中的两条单独的路由