在使用 PyInstaller 打包我的 Python 应用程序时,遇到了一个 FileNotFoundError。具体错误信息如下:

FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'C:\\Users\\linds\\AppData\\Local\\Temp\\_MEI17202\\utils\\general.pyc'

问题分析

这个错误通常是由于 PyInstaller 在打包过程中未能正确包含某些文件。具体来说,缺失的 general.pyc 文件在运行时无法找到,导致程序崩溃。

解决方案

为了解决这个问题,我修改了 .spec 文件,明确指定了缺失的文件和依赖项。以下是我所做的步骤:

1、创建 .spec 文件

	pyinstaller --onefile --name "start" start.py
  • 编辑 .spec 文件(将general.py复制一份改为general.pyc放在同级目录)

     # -*- mode: python ; coding: utf-8 -*-
     block_cipher = None
     
     a = Analysis(['start.py'],
                  pathex=['C:\\Users\\linds\\anaconda3\\envs\\py36\\Lib\\site-packages\\torch\\lib'],
                  binaries=[(r'D:\yolov5_cap\utils\general.pyc', r'.\utils')],
                  datas=[('utils/general.py', 'utils'), ('utils/general.pyc', 'utils')],
                  hiddenimports=[],
                  hookspath=[],
                  hooksconfig={},
                  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,
               a.binaries,
               a.zipfiles,
               a.datas,
               [],
               name='start',
               debug=False,
               bootloader_ignore_signals=False,
               strip=False,
               upx=True,
               upx_exclude=[],
               runtime_tmpdir=None,
               console=True,
               disable_windowed_traceback=False,
               target_arch=None,
               codesign_identity=None,
               entitlements_file=None)
    

2、移除多余的数据

我还在代码中添加了条件,删除了不必要的 .pyd 文件,确保只包含所需的文件。

3、打包应用程序

pyinstaller start.spec

结果

通过这些修改,成功解决了 FileNotFoundError 问题,并顺利生成了可执行文件。在运行生成的程序时,没有出现文件找不到的错误。

总结

在使用 PyInstaller 打包 Python 应用程序时,确保所有依赖和文件都正确包含在内是至关重要的。通过编辑 .spec 文件,我们可以灵活地添加缺失的文件,从而避免运行时错误。这次经验让我更加熟悉了 PyInstaller 的使用,也为未来的项目提供了宝贵的参考。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐