|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import os |
3 | 4 | import runpy |
4 | 5 | import sys |
5 | 6 | from pathlib import Path |
6 | 7 |
|
7 | 8 | BACKEND_DIR = Path(__file__).resolve().parent |
8 | 9 | APP_DIR = BACKEND_DIR / "app" |
| 10 | +_WINDOWS_DLL_DIRECTORY_HANDLES: list[object] = [] |
| 11 | + |
| 12 | + |
| 13 | +def configure_windows_dll_search_path() -> None: |
| 14 | + if sys.platform != "win32" or not hasattr(os, "add_dll_directory"): |
| 15 | + return |
| 16 | + |
| 17 | + runtime_executable_dir = Path(sys.executable).resolve().parent |
| 18 | + candidates = [ |
| 19 | + runtime_executable_dir, |
| 20 | + runtime_executable_dir / "DLLs", |
| 21 | + BACKEND_DIR / "python", |
| 22 | + BACKEND_DIR / "python" / "DLLs", |
| 23 | + ] |
| 24 | + |
| 25 | + normalized_added: set[str] = set() |
| 26 | + path_entries: list[str] = [] |
| 27 | + for candidate in candidates: |
| 28 | + if not candidate.is_dir(): |
| 29 | + continue |
| 30 | + candidate_str = str(candidate) |
| 31 | + candidate_key = candidate_str.lower() |
| 32 | + if candidate_key in normalized_added: |
| 33 | + continue |
| 34 | + normalized_added.add(candidate_key) |
| 35 | + path_entries.append(candidate_str) |
| 36 | + try: |
| 37 | + _WINDOWS_DLL_DIRECTORY_HANDLES.append( |
| 38 | + os.add_dll_directory(candidate_str), |
| 39 | + ) |
| 40 | + except OSError: |
| 41 | + continue |
| 42 | + |
| 43 | + if path_entries: |
| 44 | + existing_path = os.environ.get("PATH", "") |
| 45 | + os.environ["PATH"] = ( |
| 46 | + ";".join(path_entries + [existing_path]) |
| 47 | + if existing_path |
| 48 | + else ";".join(path_entries) |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +configure_windows_dll_search_path() |
9 | 53 |
|
10 | 54 | sys.path.insert(0, str(APP_DIR)) |
11 | 55 |
|
|
0 commit comments