-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwindows_dll_manager.py
More file actions
65 lines (51 loc) · 1.9 KB
/
windows_dll_manager.py
File metadata and controls
65 lines (51 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
import sys
import contextlib
def get_dll_paths():
pycppad_paths = os.getenv("PYCPPAD_WINDOWS_DLL_PATH")
if pycppad_paths is None:
# From https://peps.python.org/pep-0250/#implementation
# lib/python-version/site-packages/package
RELATIVE_DLL_PATH1 = "..\\..\\..\\..\\bin"
# lib/site-packages/package
RELATIVE_DLL_PATH2 = "..\\..\\..\\bin"
# For unit test
RELATIVE_DLL_PATH3 = "..\\..\\bin"
return [
os.path.join(os.path.dirname(__file__), RELATIVE_DLL_PATH1),
os.path.join(os.path.dirname(__file__), RELATIVE_DLL_PATH2),
os.path.join(os.path.dirname(__file__), RELATIVE_DLL_PATH3),
]
else:
return pycppad_paths.split(os.pathsep)
class PathManager(contextlib.AbstractContextManager):
"""Restore PATH state after importing Python module"""
def add_dll_directory(self, dll_dir: str):
os.environ["PATH"] += os.pathsep + dll_dir
def __enter__(self):
self.old_path = os.environ["PATH"]
return self
def __exit__(self, *exc_details):
os.environ["PATH"] = self.old_path
class DllDirectoryManager(contextlib.AbstractContextManager):
"""Restore DllDirectory state after importing Python module"""
def add_dll_directory(self, dll_dir: str):
# add_dll_directory can fail on relative path and non
# existing path.
# Since we don't know all the fail criterion we just ignore
# thrown exception
try:
self.dll_dirs.append(os.add_dll_directory(dll_dir))
except OSError:
pass
def __enter__(self):
self.dll_dirs = []
return self
def __exit__(self, *exc_details):
for d in self.dll_dirs:
d.close()
def build_directory_manager():
if sys.version_info >= (3, 8):
return DllDirectoryManager()
else:
return PathManager()