|
3 | 3 | import contextlib |
4 | 4 | import os |
5 | 5 | from functools import lru_cache |
6 | | -from os import getenv |
| 6 | +from os import getenv as sys_getenv |
7 | 7 | from pathlib import Path |
8 | 8 | from typing import TYPE_CHECKING, Any |
9 | 9 |
|
@@ -670,6 +670,55 @@ def ternary( |
670 | 670 | return false_callback() |
671 | 671 |
|
672 | 672 |
|
| 673 | +_ENV_PREFIX = "GPUSTACK_RUNTIME_" |
| 674 | + |
| 675 | + |
| 676 | +def getenv(key: str, default=None) -> any | None: |
| 677 | + """ |
| 678 | + Get the value of an environment variable. |
| 679 | + Try headless module variable if the key starts with "GPUSTACK_RUNTIME_". |
| 680 | +
|
| 681 | + Args: |
| 682 | + key: |
| 683 | + The environment variable key. |
| 684 | + default: |
| 685 | + The default value if the key is not found. |
| 686 | +
|
| 687 | + Returns: |
| 688 | + The value of the environment variable if it exists, otherwise None. |
| 689 | +
|
| 690 | + """ |
| 691 | + value = sys_getenv(key) |
| 692 | + if value is not None: |
| 693 | + return value |
| 694 | + if key.startswith(_ENV_PREFIX): |
| 695 | + headless_key = key.removeprefix(_ENV_PREFIX) |
| 696 | + return sys_getenv(headless_key, default) |
| 697 | + return default |
| 698 | + |
| 699 | + |
| 700 | +def getenvs(keys: list[str], default=None) -> any | None: |
| 701 | + """ |
| 702 | + Get the value of an environment variable. |
| 703 | + Return the first found value among the provided keys. |
| 704 | +
|
| 705 | + Args: |
| 706 | + keys: |
| 707 | + The environment variable key(s). |
| 708 | + default: |
| 709 | + The default value if none of the keys are found. |
| 710 | +
|
| 711 | + Returns: |
| 712 | + The value of the environment variable if it exists, otherwise None. |
| 713 | +
|
| 714 | + """ |
| 715 | + for key in keys: |
| 716 | + value = getenv(key) |
| 717 | + if value is not None: |
| 718 | + return value |
| 719 | + return default |
| 720 | + |
| 721 | + |
673 | 722 | def get_os_release() -> str: |
674 | 723 | """ |
675 | 724 | Get the operating system release information. |
|
0 commit comments