使用PyInstaller打包Python脚本为exe时遭遇ModuleNotFoundError问题
Looks like PyInstaller's automatic dependency detection missed pyautogui and its related sub-modules—this is a common issue with libraries that use dynamic imports or have nested dependencies. Here are the step-by-step fixes you can try:
1. Double-check your environment setup first
First, make sure you're working in the right Conda environment where pyautogui is actually installed:
- Activate your target environment if you haven't already:
conda activate your_env_name - Run
conda listorpip listto verifypyautoguiappears in the installed packages. If it's missing, install it via:# Using pip pip install pyautogui # Or Conda (use conda-forge since pyautogui isn't in default channels) conda install -c conda-forge pyautogui
2. Force PyInstaller to include pyautogui with hidden imports
The simplest fix is to explicitly tell PyInstaller to include pyautogui using the --hidden-import flag. Run this command instead:
pyinstaller --onefile --hidden-import pyautogui script_name.py
If you still get errors for sub-modules like pygetwindow or pyscreeze (common dependencies of pyautogui), add those too:
pyinstaller --onefile --hidden-import pyautogui --hidden-import pygetwindow --hidden-import pyscreeze --hidden-import pyrect script_name.py
3. Use a .spec file for more control (more reliable)
For a more robust solution, generate and edit a PyInstaller spec file to define all required imports:
- Generate the spec file first (without the
--onefileflag temporarily):pyinstaller script_name.py - Open the generated
script_name.specfile in a text editor. Look for thehiddenimportsline and update it to include all pyautogui-related modules:hiddenimports=['pyautogui', 'pygetwindow', 'pyscreeze', 'pyrect'], - Now package using the spec file with the
--onefileflag:pyinstaller --onefile script_name.spec
4. Try a clean Conda environment
Sometimes environment conflicts can cause PyInstaller to miss dependencies. Create a fresh environment just for packaging:
# Create a new environment (replace 3.x with your Python version) conda create -n packaging_env python=3.10 conda activate packaging_env # Install only what you need pip install pyautogui pyinstaller # Navigate to your script directory and package cd path/to/your/script/folder pyinstaller --onefile script_name.py
The core issue here is that PyInstaller relies on static code analysis to find dependencies, and some parts of pyautogui are imported dynamically—so PyInstaller can't detect them automatically. By explicitly listing the hidden imports, you're telling PyInstaller to include those modules in the final executable.
内容的提问来源于stack exchange,提问作者akkab

