首页 > 解决方案 > 使用 pyinstaller 将“.py 文件”(具有“导入栅格”)转换为“.exe 文件”时出现“导入错误:DLL 加载失败”

问题描述

我有一个3.7名为的 python (version ) 文件test.py,我想将其转换为test.exeusing pyinstaller. 当我使用命令时

pyinstaller test.py

它正在test.exe成功创建。但是当我尝试test.exe使用命令提示符执行文件时,出现以下错误:

"Traceback (most recent call last):
  File "test.py", line 1, in <module>
  File "c:\users\user1\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\rasterio\__init__.py", line 29, in <module>
ImportError: DLL load failed: The specified module could not be found.
[460] Failed to execute script test"   

在浏览了网站上的类似帖子后,我尝试了不同的选项,例如:

(i) 第一个选项:在路径中C:\Users\user1\Anaconda3\Lib\site-packages\PyInstaller\hooks我添加了一个hook-rasterio.py包含hiddenimports=['rasterio', 'rasterio._shim']然后尝试

pyinstaller -F test.py

但我仍然收到上述错误。

(ii)第二个选项:在我添加的test.spec文件中,然后使用创建但问题仍然存在。hiddenimports=[]rasteriorasterio._shimtest.exepyinstaller

我的test.py样子:

import rasterio
print("It's Done....")

任何人都可以建议可以解决问题的必要事项。

标签: pythonpyinstallerrasterio

解决方案


rasterio是一个复杂的库,它依赖于许多外部库。您的错误是 DLL 加载错误,这意味着它缺少rasterio. 我建议您按照此处的安装过程,并确保rasterio您的 conda 环境正确安装(为此使用新的 env)。

接下来,检查rasterio是否导入没有任何问题,例如:

import traceback
try:
    import rasterio
    print("Import OK!")
except ImportError:
    print("Import Error!")
    traceback.print_exc()
input()

接下来,安装 PyInstaller 并使用以下规范文件:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['test.py'],
             pathex=['C:\\Users\\Masoud\\Desktop\\test'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
a.datas += Tree('C:\\Users\\Masoud\\Anaconda3\\envs\\testEnv\\Lib\\site-packages\\rasterio\\', prefix='rasterio')
a.datas += Tree('C:\\Users\\Masoud\\Anaconda3\\envs\\testEnv\\Lib\\xml', prefix='xml')
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='test',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=False,
          runtime_tmpdir=None,
          console=True )

在上面的脚本中,我将整个rasterioxml库放在可执行文件旁边,因为 PyInstaller 无法解析模块导入。请记住根据您的设置更改路径。

最后,使用以下命令生成可执行文件:

pyinstaller test.spec

推荐阅读