Skip to content

Commit d411d66

Browse files
committedAug 21, 2020
windows: map python PATH changes to Add/RemoveDllDirectory (followup f17097b; fixes #38372)
1 parent d1c45f8 commit d411d66

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
 

‎python/utils.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,9 +711,36 @@ def __enter__(self):
711711
def __exit__(self, exc_type, exc_val, exc_tb):
712712
QApplication.restoreOverrideCursor()
713713

714+
714715
#######################
715716
# IMPORT wrapper
716717

718+
if os.name == 'nt' and sys.version_info < (3, 8):
719+
import ctypes
720+
from ctypes import windll, wintypes
721+
722+
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
723+
724+
_hasAddDllDirectory = hasattr(kernel32, 'AddDllDirectory')
725+
if _hasAddDllDirectory:
726+
_import_path = os.environ['PATH']
727+
_import_paths = {}
728+
729+
def _errcheck_zero(result, func, args):
730+
if not result:
731+
raise ctypes.WinError(ctypes.get_last_error())
732+
return args
733+
734+
DLL_DIRECTORY_COOKIE = wintypes.LPVOID
735+
736+
_AddDllDirectory = kernel32.AddDllDirectory
737+
_AddDllDirectory.errcheck = _errcheck_zero
738+
_AddDllDirectory.restype = DLL_DIRECTORY_COOKIE
739+
_AddDllDirectory.argtypes = (wintypes.LPCWSTR,)
740+
741+
_RemoveDllDirectory = kernel32.RemoveDllDirectory
742+
_RemoveDllDirectory.errcheck = _errcheck_zero
743+
_RemoveDllDirectory.argtypes = (DLL_DIRECTORY_COOKIE,)
717744

718745
_uses_builtins = True
719746
try:
@@ -740,6 +767,30 @@ def _import(name, globals={}, locals={}, fromlist=[], level=None):
740767
'Use {} or the version independent {} import instead.'.format(name.replace('PyQt4', 'PyQt5'), name.replace('PyQt4', 'qgis.PyQt'))
741768
raise ImportError(msg)
742769

770+
if os.name == 'nt' and sys.version_info < (3, 8):
771+
global _hasAddDllDirectory
772+
if _hasAddDllDirectory:
773+
global _import_path
774+
global _import_paths
775+
776+
old_path = _import_path
777+
new_path = os.environ['PATH']
778+
if old_path != new_path:
779+
global _AddDllDirectory
780+
global _RemoveDllDirectory
781+
782+
for p in set(new_path.split(';')) - set(old_path.split(';')):
783+
if p:
784+
qDebug(u"AddDllDirectory:{}".format(p))
785+
_import_paths[p] = _AddDllDirectory(p)
786+
787+
for p in set(old_path.split(';')) - set(new_path.split(';')):
788+
if p in _import_paths:
789+
qDebug(u"RemoveDllDirectory:{}".format(p))
790+
_RemoveDllDirectory(_import_paths.pop(p))
791+
792+
_import_path = new_path
793+
743794
mod = _builtin_import(name, globals, locals, fromlist, level)
744795

745796
if mod and '__file__' in mod.__dict__:

0 commit comments

Comments
 (0)
Please sign in to comment.