diff --git a/win32/Lib/pywin32_bootstrap.py b/win32/Lib/pywin32_bootstrap.py index 0161f27aff..0531db66ad 100644 --- a/win32/Lib/pywin32_bootstrap.py +++ b/win32/Lib/pywin32_bootstrap.py @@ -8,7 +8,7 @@ try: import pywin32_system32 -except ImportError: # Python ≥3.6: replace ImportError with ModuleNotFoundError +except ImportError: pass else: import os @@ -17,5 +17,19 @@ # https://docs.python.org/3/reference/import.html#path-attributes-on-modules for path in pywin32_system32.__path__: if os.path.isdir(path): - os.add_dll_directory(path) + # First try the preferred method + if hasattr(os, "add_dll_directory"): + os.add_dll_directory(path) + # If `add_dll_directory` is missing, which can happen in Pylance early initialization, + # try to modify PATH if it exists (just create it if it doesn't) + elif "PATH" not in os.environ: + os.environ["PATH"] = path + else: + # This is to ensure the pywin32 path is in the beginning to find the + # pywin32 DLLs first and prevent other PATH entries to shadow them + prepend_to_path = path + os.pathsep + if not os.environ["PATH"].startswith(prepend_to_path): + os.environ["PATH"] = prepend_to_path + os.environ["PATH"].replace( + os.pathsep + path, "" + ) break