sqlite + PyQt5 to standalone exe - Python 3.6.3 + Pyinstaller

白昼怎懂夜的黑 提交于 2020-01-21 09:47:26

问题


I would like to create an exe with Pyinstaller including a database (.db) and a picture (.png). I want everything into a single exe (--onefile). I tried to add the path of both elements directly in the spec file but it doesn't work.

Here is my spec file:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['back_end.py'],
             pathex=['C:\\Users\\...\\site-packages\\PyQt5\\Qt\\bin', 'C:\\Users\\...\\Test_packaging'],
             binaries=[],
             datas=['C:\\Users\...\\Test_packaging\\database1.db', 'C:\\Users\...\\Test_packaging\\picture1.png'],
             hiddenimports=[],
             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='back_end',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=False )

Thank you


回答1:


You have to solve many issues to get this working. For example:

  • Getting the right resource path
  • Adding data

The first issue is solved by adjusting paths depending on execution mode.

def app_path(path):
    frozen = 'not'
    if getattr(sys, 'frozen', False):
            # we are running in executable mode
            frozen = 'ever so'
            app_dir = sys._MEIPASS
    else:
            # we are running in a normal Python environment
            app_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(app_dir, path)

The second issue is efficiently including what you need. At first the obvious solution is to add each image and db manually, but i had lots of image. I turned to the spec file way using the wildcard operator (*) to add what i need in folder than adding folder/*.

added_files = [
         ( './pics/*', 'pics' ),
         ( './db/*', 'db' ),
         ]

then in Analysis,

datas = added_files

A thorough answer is quite long. I've written this article to show in some minute details what i went through to solve the issue.



来源:https://stackoverflow.com/questions/47114772/sqlite-pyqt5-to-standalone-exe-python-3-6-3-pyinstaller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!