PyInstaller与PyCryptoDome不兼容?使用时遇ImportError如何解决?
Hey there, let's work through this ImportError issue step by step—this is a common pain point when combining PyInstaller and PyCryptoDome on Python 2.7, especially on Windows. Here's what you can try:
1. Ensure You're Installing the Correct PyCryptoDome Version for Python 2.7
Python 2.7 is end-of-life, and newer PyCryptoDome versions (4.x+) drop support for it. First, uninstall any conflicting packages and install the last compatible version:
pip uninstall -y pycrypto pycryptodome pycryptodomex pip install pycryptodome==3.9.9
After installing, test the import directly in your Python 2.7 shell to confirm it works:
from Crypto.Cipher import AES # Should not throw an error
If this fails here, the issue is with the installation, not PyInstaller. Double-check you're using the correct pip (use pip2 if you have multiple Python versions installed).
2. Fix PyInstaller's Hidden Imports
PyInstaller often misses submodules from PyCryptoDome because they're loaded dynamically. You have two ways to fix this:
Option A: Use the --hidden-import Flag When Packing
Add all required PyCryptoDome submodules to your PyInstaller command. For example, if you're using AES and SHA256:
pyinstaller --hidden-import Crypto.Cipher.AES --hidden-import Crypto.Hash.SHA256 your_script.py
List all used submodules with separate --hidden-import flags.
Option B: Modify the PyInstaller Spec File
For more control, generate a spec file first, then edit it to include hidden imports:
- Generate the spec file:
pyinstaller --name your_app your_script.py - Open
your_app.specin a text editor, find thehiddenimportslist, and add necessary Crypto submodules:hiddenimports=['Crypto.Cipher.AES', 'Crypto.Hash.SHA256', 'Crypto.Util.Padding'], - Repack using the spec file:
pyinstaller your_app.spec
3. Add PyCryptoDome's Installation Path to PyInstaller's Search Path
Sometimes PyInstaller can't locate the Crypto package even if it's installed. Find where PyCryptoDome is installed (run pip show pycryptodome and copy the Location path), then add it to the pathex in your spec file:
pathex=['C:\\Python27\\Lib\\site-packages'], # Replace with your actual path
Use double backslashes for Windows paths, or a raw string (r'C:\Python27\Lib\site-packages').
4. Clean Up Old Build Files and Repack
PyInstaller caches build files, which can cause stale references. Delete the build/, dist/, and your_app.spec (if regenerating) folders/files, then run your PyInstaller command again from scratch.
5. Verify PyInstaller Uses the Correct Python Interpreter
If the import works in your shell but not the packed app, confirm PyInstaller is tied to Python 2.7. Run pyinstaller --version to check, or use the full path to Python 2.7's PyInstaller:
C:\Python27\Scripts\pyinstaller.exe your_command_here
内容的提问来源于stack exchange,提问作者jason steph

