python - 使用 PyInstaller 打包后 PySide2 应用程序中的路径错误

标签 python pyinstaller pyside2

我正在尝试使用以下结构打包 PySide2 测试应用程序:

.
├── main.py
├── main.spec
└── wizardUI
    ├── 10.toolBoxBtns.ui
    ├── 11.toolBoxShrCt.ui
    ├── 12.propertyBox.ui
    ├── 13.printing.ui
    ├── 14.settings.ui
    ├── 15.coclusion.ui
    ├── 1.welcomePage.ui
    ├── 2.graphicsScene.ui
    ├── 3.graphicsSceneText.ui
    ├── 4.textDialog.ui
    ├── 5.codeDialog.ui
    ├── 6.graphicsSceneBox.ui
    ├── 7.graphicsScenePixmap.ui
    ├── 8.graphicsSceneShrCt.ui
    ├── 9.toolbox.ui
    └── wizard.py

当我尝试运行可执行文件时,出现此错误:

FileNotFoundError: No such file or directory:'/home/artem/Desktop/testUI/dist/main/wizardUI'

这是我的 Wizard.py 文件

from PySide2 import QtCore, QtWidgets
from PySide2.QtUiTools import QUiLoader
import os


class tutorWizard(QtWidgets.QWizard):
    """ Contains introduction tutorial """
    def __init__(self, parent=None):
        super(tutorWizard, self).__init__(parent)


        self.setWindowTitle("Introduction tutorial")
        pages = self.findPages()
        self.initPages(pages)

    def findPages(self):
        ui_files = []
        cnt = 1
        current_dir = os.path.dirname(os.path.realpath(__file__))
        while len(ui_files) != 15:
            for file in os.listdir(current_dir):
                if file.startswith("{}.".format(cnt)):
                    ui_files.append(os.path.join(current_dir, file))
                    cnt += 1
        return ui_files

    def initPages(self, files):
        loader = QUiLoader()
        for i in files:
            file = QtCore.QFile(str(i))
            file.open(QtCore.QFile.ReadOnly)

            file.reset()
            page = loader.load(file)

            file.close()

            self.addPage(page)

main.py 是:

from PySide2.QtWidgets import QApplication
from wizardUI.wizard import tutorWizard
import sys


app = QApplication(sys.argv)
window = tutorWizard()
window.show()
sys.exit(app.exec_())

.spec 文件是:

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['main.py'],
             pathex=['/home/artem/Desktop/testUI'],
             binaries=[],
             datas=[],
             hiddenimports=['PySide2.QtXml'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='main')

a.datas += Tree('/home/artem/Desktop/testUI/wizardUI')

有没有办法在不更改 wizard.py 中的 current_dir 变量的情况下解决此错误?

最佳答案

您的代码存在以下问题:

  • 您在 COLLECT 之后将 Tree() 添加到 a.datas,因此它不会在编译中使用,您必须在之前添加它。

  • 您不能再使用 __file__ 来获取目录路径,而是必须使用 sys._MEIPASS .

我还将给出以下改进:

  • 为了使 .spec 易于移植,我将使用 SPECPATH变量。
  • 我添加了第二个参数“wizardUI”来创建带有 .ui 的字典,我还排除了 Wizard.py。

综合以上情况,解决方案如下:

ma​​in.py

from PySide2.QtWidgets import QApplication
from wizardUI.wizard import tutorWizard
import sys


if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = tutorWizard()
    window.show()
    sys.exit(app.exec_())

wizard.py

import os
import sys

from PySide2 import QtCore, QtWidgets, QtUiTools

# https://stackoverflow.com/a/42615559/6622587
if getattr(sys, 'frozen', False):
    # If the application is run as a bundle, the pyInstaller bootloader
    # extends the sys module by a flag frozen=True and sets the app 
    # path into variable _MEIPASS'.
    current_dir = os.path.join(sys._MEIPASS, "wizardUI")
else:
    current_dir = os.path.dirname(os.path.abspath(__file__))


class tutorWizard(QtWidgets.QWizard):
    """ Contains introduction tutorial """

    def __init__(self, parent=None):
        super(tutorWizard, self).__init__(parent)

        self.setWindowTitle("Introduction tutorial")
        pages = self.findPages()
        self.initPages(pages)

    def findPages(self):
        ui_files = []
        cnt = 1
        while len(ui_files) < 15:
            for file in os.listdir(current_dir):
                if file.startswith("{}.".format(cnt)):
                    ui_files.append(os.path.join(current_dir, file))
                    cnt += 1
        return ui_files

    def initPages(self, files):
        loader = QtUiTools.QUiLoader()
        for i in files:
            file = QtCore.QFile(str(i))
            if file.open(QtCore.QFile.ReadOnly):
                page = loader.load(file)
                self.addPage(page)

ma​​in.spec

# -*- mode: python ; coding: utf-8 -*-

# https://stackoverflow.com/a/50402636/6622587
import os
spec_root = os.path.abspath(SPECPATH)

block_cipher = None

a = Analysis(['main.py'],
             pathex=[spec_root],
             binaries=[],
             datas=[],
             hiddenimports=['PySide2.QtXml', 'packaging.specifiers', 'packaging.requirements'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True )

a.datas += Tree(os.path.join(spec_root, 'wizardUI'), 'wizardUI', excludes=["*.py"])

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='main')
<小时/>

另一个选择是使用 Qt Resource而不是数据。

资源.qrc

<RCC>
  <qresource prefix="/">
    <file>wizardUI/1.welcomePage.ui</file>
    <file>wizardUI/2.graphicsScene.ui</file>
    <file>wizardUI/3.graphicsSceneText.ui</file>
    <file>wizardUI/4.textDialog.ui</file>
    <file>wizardUI/5.codeDialog.ui</file>
    <file>wizardUI/6.graphicsSceneBox.ui</file>
    <file>wizardUI/7.graphicsScenePixmap.ui</file>
    <file>wizardUI/8.graphicsSceneShrCt.ui</file>
    <file>wizardUI/9.toolbox.ui</file>
    <file>wizardUI/10.toolBoxBtns.ui</file>
    <file>wizardUI/11.toolBoxShrCt.ui</file>
    <file>wizardUI/12.propertyBox.ui</file>
    <file>wizardUI/13.printing.ui</file>
    <file>wizardUI/14.settings.ui</file>
    <file>wizardUI/15.coclusion.ui</file>
  </qresource>
</RCC>

然后使用 pyside2-rcc 将其转换为 .py:

pyside2-rcc resource.qrc -o resource_rc.py

然后你必须修改脚本:

ma​​in.py

from PySide2.QtWidgets import QApplication
from wizardUI.wizard import tutorWizard
import sys

import resource_rc

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = tutorWizard()
    window.show()
    sys.exit(app.exec_())

wizard.py

from PySide2 import QtCore, QtWidgets, QtUiTools


class tutorWizard(QtWidgets.QWizard):
    """ Contains introduction tutorial """

    def __init__(self, parent=None):
        super(tutorWizard, self).__init__(parent)

        self.setWindowTitle("Introduction tutorial")
        pages = self.findPages()
        self.initPages(pages)

    def findPages(self):
        ui_files = []
        cnt = 1
        while len(ui_files) < 15:
            it = QtCore.QDirIterator(":/wizardUI")
            while it.hasNext():
                filename = it.next()
                name = QtCore.QFileInfo(filename).fileName()
                if name.startswith("{}.".format(cnt)):
                    ui_files.append(filename)
                    cnt += 1                    
        return ui_files

    def initPages(self, files):
        loader = QtUiTools.QUiLoader()
        for i in files:
            file = QtCore.QFile(str(i))
            if file.open(QtCore.QFile.ReadOnly):
                page = loader.load(file)
                self.addPage(page)

最后您的项目结构如下:

├── main.py
├── main.spec
├── resource.qrc
├── resource_rc.py
└── wizardUI
    ├── 10.toolBoxBtns.ui
    ├── 11.toolBoxShrCt.ui
    ├── 12.propertyBox.ui
    ├── 13.printing.ui
    ├── 14.settings.ui
    ├── 15.coclusion.ui
    ├── 1.welcomePage.ui
    ├── 2.graphicsScene.ui
    ├── 3.graphicsSceneText.ui
    ├── 4.textDialog.ui
    ├── 5.codeDialog.ui
    ├── 6.graphicsSceneBox.ui
    ├── 7.graphicsScenePixmap.ui
    ├── 8.graphicsSceneShrCt.ui
    ├── 9.toolbox.ui
    └── wizard.py
<小时/>

两个解决方案均已找到 here

关于python - 使用 PyInstaller 打包后 PySide2 应用程序中的路径错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185927/

相关文章:

python - 如何重置从 ipywidget 命令按钮生成的输出,以便仅显示更新的 DataFrame?

python - 使用 Python Gspread 访问 Google Drive 电子表格

python - Pyinstaller 失败,因为在 Windows 上找不到 pyconfig.h

python - 脚本卡在 try- except block 中

python - 如何使用 pyinstaller 将包转换为 exe?

Pyinstaller 和 R6034 错误

Python PyQt 信号并不总是有效

python - Matplotlib事件处理: when do they send matplotlib events and when Qt events

python - PySide2 将鼠标事件传递给系统

python - 如何将百万歌曲数据集等大数据集加载到 BigData HDFS 或 Hbase 或 Hive 中?