Visual Servoing Platform version 3.7.0
Loading...
Searching...
No Matches
windows_dll_manager.py
1'''
2This code is directly adapted from proxsuite_nlp, see:
3
4- https://github.com/Simple-Robotics/proxsuite-nlp/blob/main/bindings/python/proxsuite_nlp/windows_dll_manager.py
5- https://github.com/Simple-Robotics/proxsuite-nlp/blob/main/bindings/python/proxsuite_nlp/__init__.py
6
7On windows, since Python 3.8, dll directories must be explicetly specified (cannot go through path), see
8- https://docs.python.org/3/library/os.html#os.add_dll_directory
9
10'''
11
12
13import os
14import sys
15import contextlib
16
17
19 # Assumes that we are in a conda environment, and that ViSP DLLs and the dependencies are installed in this environment
20 # For the choice of defaults: see https://peps.python.org/pep-0250/#implementation
21 DEFAULT_DLL_PATHS = [
22 '..\\..\\..\\..\\bin', # when current folder is lib/python-version/site-packages/package
23 '..\\..\\..\\..\\Library\\bin',
24 '..\\..\\..\\bin', # when current folder is lib/site-packages/package
25 '..\\..\\..\\Library\\bin',
26 ]
27 # If we have a different setup, the user should specify their own paths
28 visp_user_defined_dll_paths = os.getenv("VISP_WINDOWS_DLL_PATH")
29 dll_paths = [
30 os.path.join(os.path.dirname(__file__), dll_path) for dll_path in DEFAULT_DLL_PATHS
31 ]
32
33 if visp_user_defined_dll_paths is not None:
34 dll_paths.extend(visp_user_defined_dll_paths.split(os.pathsep))
35
36 return dll_paths
37
38class PathManager(contextlib.AbstractContextManager):
39 """Restore PATH state after importing Python module"""
40
41 def add_dll_directory(self, dll_dir: str):
42 os.environ["PATH"] += os.pathsep + dll_dir
43
44 def __enter__(self):
45 self.old_path = os.environ["PATH"]
46 return self
47
48 def __exit__(self, *exc_details):
49 os.environ["PATH"] = self.old_path
50
51
52class DllDirectoryManager(contextlib.AbstractContextManager):
53 """Restore DllDirectory state after importing Python module"""
54
55 def add_dll_directory(self, dll_dir: str):
56 # add_dll_directory can fail on relative path and non
57 # existing path.
58 # Since we don't know all the fail criterion we just ignore
59 # thrown exception
60 try:
61 self.dll_dirs.append(os.add_dll_directory(dll_dir))
62 except OSError:
63 pass
64
65 def __enter__(self):
66 self.dll_dirs = []
67 return self
68
69 def __exit__(self, *exc_details):
70 for d in self.dll_dirs:
71 d.close()
72
73
75 if sys.version_info >= (3, 8):
76 return DllDirectoryManager()
77 else: # Below 3.8, the path variable is used to search for DLLs
78 return PathManager()