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