PyInstaller won't import pywin32 / win32clipboard – ImportError upon running executable

Question:

I’m working in Windows 10 with Python 3.8.6 and using PyInstaller 4.0 to compile my script as an executable for distribution. I just added a feature today that required importing win32clipboard. PyInstaller finishes compiling without any errors, but the excecutable fails to load due to:

ImportError: DLL load failed while importing win32clipboard: The specified module could not be found.

I attempted to compile the program again using the hidden-import flag:

pyinstaller myscript.py --onefile --hidden-import win32clipboard

This produced the same result and an ImportError upon trying to load the program (no errors during compiling).

I know that win32clipboard is part of pywin32 and my program compiled and ran without any issues prior to the code changes that required importing it. It still runs fine out of IDLE and functions as intended when using the win32clipboard-enabled features.

Is there some way to manually direct PyInstaller to import this correctly, or some other way to fix this issue and get the executable working again?

Asked By: DJT

||

Answers:

I was able to work around this issue by importing pywintypes into my script before win32clipboard.

import pywintypes
import win32clipboard

Found the suggestion in an old GitHub bug report for an issue people were having importing win32api with PyInstaller and decided to give it a try. I was able to compile and run my program without any issues after doing this.

Answered By: DJT

Working with PyInstaller: 5.1, Python: 3.8.12 (conda), and Platform: Windows-10.

In addition to the solution from @DJT of importing pywintypes before win32clipboard, I solved the same error by downgrading my pywin32 from version 228 to version 225. Just type the following command with the building environment active:

pip install --upgrade --user  pywin32==225
Answered By: Rayco