gpt4 book ai didi

python - 有人成功地使用 Pyinstaller 将数据文件捆绑到一个文件中吗?

转载 作者:太空狗 更新时间:2023-10-29 21:05:06 25 4
gpt4 key购买 nike

我一直在梳理 Stack Overflow 和网络的其余部分,了解如何将数据文件添加到我的 Python 应用程序中:

import Tkinter

class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()

def initialize(self):
self.grid()

--- Everything Fine Here ---

self.B = Tkinter.Button(self, text = 'Create Document', command = self.OnButtonClick)
self.B.grid(column = 0, row = 6)


def OnButtonClick(self):
createDoc()

if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('Receipt Form')
app.iconbitmap(os.getcwd() + '/M.ico')
app.mainloop()

我尝试过使用 .spec 文件,但没有成功

Onedir 工作正常,但是当我尝试编译成单个可执行文件时,它给出了一个错误,指出文件“M.ico”未定义。

如果有人能够使用 pyinstaller 将数据文件捆绑到一个文件中。请帮忙。谢谢。

我在一台运行 Python 2.7 和 PyInstaller 3.2 的 Windows 10 计算机上

最佳答案

您必须在 pyinstaller .spec 文件中指定要添加的每个数据文件,或通过命令行选项(.spec 更容易。)下面是我的 .spec 文件,带有“datas”部分:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['pubdata.py'],
pathex=['.', '/interface','/recommender'],
binaries=None,
datas=[('WordNet/*.txt','WordNet'),
('WordNet/*.json','WordNet'),
('WordNet/pdf_parsing/*.json','pdf_parsing'),
('WordNet/pdf_parsing/*.xml','pdf_parsing'),
('images/*.png','images'),
('database/all_meta/Flybase/*.txt','all_meta'),
('database/all_meta/Uniprot/*.txt','all_meta'),
('database/json_files/*.json','json_files'),
('Data.db','.')],

hiddenimports=['interface','recommender'],
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,
exclude_binaries=True,
name='GUI',
debug=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
name='GUI')
app = BUNDLE(coll,
name='App.app',
icon=None)

在此之后,如果您尝试访问您在 .spec 文件中指定的任何数据文件,则必须在您的代码中使用 Pyinstaller 的 _MEIPASS 文件夹来引用您的文件。以下是我如何处理名为 Data.db 的文件:

import sys
import os.path

if hasattr(sys, "_MEIPASS"):
datadir = os.path.join(sys._MEIPASS, 'Data.db')
else:
datadir = 'Data.db'

conn = lite.connect(datadir)

上面的这个方法替换了这个独立的语句:

conn = lite.connect("Data.db")

当我经历同样的事情时,这个链接对我帮助很大: https://irwinkwan.com/2013/04/29/python-executables-pyinstaller-and-a-48-hour-game-design-compo/

希望对您有所帮助!

关于python - 有人成功地使用 Pyinstaller 将数据文件捆绑到一个文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com