You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Poetry环境下PyInstaller编译报错:pyi_rth_pkgres导入失败

本地Poetry环境下PyInstaller编译报错:pyexpat DLL找不到

我用Poetry管理的虚拟环境编译Python应用,同一个spec文件在GitHub Actions里能正常编译,但本地运行pyinstaller --clean app.spec时,先弹出无法识别conda环境的警告,运行编译后的exe又报ImportError,提示找不到pyexpat的DLL。已经试过添加setuptools依赖,问题仍未解决。

我的spec文件

# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import copy_metadata
import sys
sys.setrecursionlimit(5000)

datas = []
datas += copy_metadata('pkg', recursive = True)

a = Analysis(
    ['app.py'],
    pathex=[],
    binaries=[],
    datas=[],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)
pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.datas,
    [],
    name='pkg',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

编译时的警告

219 WARNING: Assuming this is not an Anaconda environment or an additional venv/pipenv/... 
environment manager is being used on top, because the conda-meta folder
C:\Users\XXXX\AppData\Local\pypoetry\Cache\virtualenvs\venv\conda-meta does not exist.

运行exe时的报错

Traceback (most recent call last):
File "PyInstaller\hooks\rthooks\pyi_rth_pkgrespy", line 158, in <module>
File "PyInstaller \hooks \rthooks\pyi_rth_pkgres.py" line 36, in _pyi_rthook
File "PyInstaller\loader \pyimode2_importers .py", line 419, in exec _module
File "pkg _resources\__init__py", line 63, in <module>
File "PyInstaller \loader \pyimod02_importers.py", line 419, in exec _module
File "plistlib.py", line 70, in <module>
File "PyInstaller\loader \pyimode2_importers py", line 419, in exec_ module
File "xml \parsers \expat.py" line 4, in <module>
ImportError: DLL load failed while importing pyexpat: The specified module could not be found.
[22988] Failed to execute script "pyi rth_pkgres" due to unhandled exception!

解决方法

  • 手动添加pyexpat依赖DLL:找到Poetry虚拟环境DLLs目录下的expat.dll,在spec文件的binaries列表中添加路径:
    binaries=[
        (r'C:\Users\XXXX\AppData\Local\pypoetry\Cache\virtualenvs\venv\DLLs\expat.dll', '.')
    ],
    
  • 添加pyexpat到隐藏导入:在spec的hiddenimports中加入pyexpat:
    hiddenimports=['pyexpat'],
    
  • 临时禁用UPX压缩:把spec里的upx=True改为upx=False,重新编译排查是否是UPX损坏了DLL。
  • 重建干净的Poetry环境:执行poetry env remove python && poetry install重新创建虚拟环境,再用pyinstaller --clean --noconfirm app.spec重新编译。
  • 跳过conda环境检测:运行PyInstaller时加--no-conda参数:pyinstaller --clean --no-conda app.spec,消除警告同时避免环境检测干扰。

内容的提问来源于stack exchange,提问作者Dushyant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 05:30:12