使用 PyInstaller (--onefile) 捆绑数据文件 [英] Bundling data files with PyInstaller (--onefile)

查看:101
本文介绍了使用 PyInstaller (--onefile) 捆绑数据文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyInstaller 构建一个包含图像和图标的单文件 EXE.我一生都无法让它与 --onefile 一起工作.

I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

如果我做 --onedir 它工作得很好.当我使用 --onefile 时,它找不到引用的附加文件(运行编译的 EXE 时).它找到了 DLL 和其他一切正常的东西,只是没有找到两个图像.

If I do --onedir it works all works very well. When I use --onefile, it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.

我查看了运行 EXE 时生成的临时目录(例如 \Temp\_MEI95642\),文件确实在那里.当我将 EXE 放在那个临时目录中时,它会找到它们.非常令人费解.

I've looked in the temp-dir generated when running the EXE (\Temp\_MEI95642\ for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.

这是我添加到 .spec 文件中的内容

This is what I've added to the .spec file

a.datas += [('images/icon.ico', 'D:\\[workspace]\\App\\src\\images\\icon.ico',  'DATA'),
('images/loaderani.gif','D:\\[workspace]\\App\\src\\images\\loaderani.gif','DATA')]     

我应该补充一点,我也尝试不将它们放在子文件夹中,没有任何区别.

I should add that I have tried not putting them in subfolders as well, didn't make a difference.

由于 PyInstaller 更新,将较新的答案标记为正确.

推荐答案

较新版本的 PyInstaller 不再设置 env 变量,因此 Shish 出色的 answer 将不起作用.现在路径被设置为 sys._MEIPASS:

Newer versions of PyInstaller do not set the env variable anymore, so Shish's excellent answer will not work. Now the path gets set as sys._MEIPASS:

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

这篇关于使用 PyInstaller (--onefile) 捆绑数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆