forked from ni/nidaqmx-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_dotenv_path.py
More file actions
73 lines (53 loc) · 2.25 KB
/
_dotenv_path.py
File metadata and controls
73 lines (53 loc) · 2.25 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
66
67
68
69
70
71
72
73
from __future__ import annotations
import inspect
import sys
import traceback
from pathlib import Path
def get_dotenv_search_path() -> Path:
"""Get the search path for loading the `.env` file."""
# Prefer to load the `.env` file from the current directory or its parents.
# If the current directory doesn't have a `.env` file, fall back to the
# script/EXE path or the TestStand code module path.
cwd = Path.cwd()
if not _has_dotenv_file(cwd):
if script_or_exe_path := _get_script_or_exe_path():
return script_or_exe_path.resolve().parent
if caller_path := _get_caller_path():
return caller_path.resolve().parent
return cwd
def _has_dotenv_file(dir: Path) -> bool:
"""Check whether the dir or its parents contains a `.env` file."""
return (dir / ".env").exists() or any((p / ".env").exists() for p in dir.parents)
def _get_script_or_exe_path() -> Path | None:
"""Get the path of the top-level script or PyInstaller EXE, if possible."""
if getattr(sys, "frozen", False):
return Path(sys.executable)
main_module = sys.modules.get("__main__")
if main_module:
script_path = getattr(main_module, "__file__", "")
if script_path:
return Path(script_path)
return None
def _get_caller_path() -> Path | None:
"""Get the path of the module calling into this package, if possible."""
package_path = _get_package_path()
for frame, _ in traceback.walk_stack(inspect.currentframe()):
if frame.f_code.co_filename:
module_path = Path(frame.f_code.co_filename)
if _exists(module_path) and not module_path.is_relative_to(package_path):
return module_path
return None
# Path.exists() throws OSError when the path has invalid file characters.
# https://github.com/python/cpython/issues/79487
if sys.version_info >= (3, 10):
def _exists(path: Path) -> bool:
return path.exists()
else:
def _exists(path: Path) -> bool:
import os
return os.path.exists(path)
def _get_package_path() -> Path:
"""Get the path of this package."""
module = sys.modules[__package__]
assert module.__file__ and module.__file__.endswith("__init__.py")
return Path(module.__file__).parent