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

PyInstaller报错AttributeError:无法获取pythoncom模块的__file__属性

解决PyInstaller打包时AttributeError: Failed to retrieve attribute __file__ from module pythoncom错误

以下是几个针对性的排查和解决方法:

  • 确认Python环境一致性
    检查Spyder使用的Python解释器和调用PyInstaller的解释器是否为同一版本:

    • 在Spyder控制台执行 import sys; print(sys.executable),记录路径
    • 在系统命令行先执行 where python(Windows)或 which python(Linux/macOS),确认当前默认Python路径,再执行 pyinstaller --version
      若路径不一致,在Spyder中切换到对应解释器,或者用该解释器的pip重新安装PyInstaller和pywin32。
  • 手动指定pythoncom模块的打包配置
    在打包脚本(.spec文件)中手动补充pythoncom的依赖配置,确保PyInstaller能正确识别它的文件属性:

    from PyInstaller.utils.hooks import collect_data_files, collect_submodules
    import pythoncom
    
    a = Analysis(
        ['你的脚本文件名.py'],
        pathex=[],
        binaries=[],
        datas=collect_data_files('pythoncom'),
        hiddenimports=collect_submodules('pythoncom') + ['pythoncom'],
        hookspath=[],
        hooksconfig={},
        runtime_hooks=[],
        excludes=[],
        win_no_prefer_redirects=False,
        win_private_assemblies=False,
        cipher=None,
        noarchive=False
    )
    # 手动设置pythoncom的__file__属性
    for mod in a.pure:
        if mod.name == 'pythoncom':
            mod.__file__ = pythoncom.__file__
    

    也可以直接在命令行打包时添加参数:pyinstaller --hidden-import pythoncom --collect-data pythoncom 你的脚本文件名.py

  • 清理PyInstaller缓存
    删除项目目录下的build、dist文件夹和生成的.spec文件(若无需保留配置),然后重新执行打包命令,避免缓存的旧文件干扰模块引用。

  • 降级PyInstaller到稳定版本
    新版本PyInstaller可能和pywin32存在兼容性问题,尝试降级到之前能正常运行的版本:

    pip uninstall pyinstaller -y
    pip install pyinstaller==5.13.0  # 替换为你之前正常使用的版本号
    
  • 修复pywin32注册表项
    以管理员身份打开命令提示符,进入Python安装目录的Scripts文件夹(例如C:\Python39\Scripts),执行:

    python pywin32_postinstall.py -install
    

    执行完成后重启Spyder和命令行窗口,再尝试打包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 06:42:11