Skip to content

Commit 5a1fa54

Browse files
committed
Support alternate ngen log path by persisting OS env var NGEN_RESULTS_DIR if already set
1 parent 856fc0e commit 5a1fa54

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

python/nwm_fcst_mgr/forecast.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from nwm_fcst_mgr.log_level import log_level_set
2020
from nwm_fcst_mgr.git_util import print_git_info_all
2121
from nwm_fcst_mgr.exceptions import NgenCalledProcessError, NgenIntentionallyStoppedError
22+
from nwm_fcst_mgr.utils import set_os_env_key, OS_ENV_KEY_RESULTS_DIR
2223

2324
# setup the logger
2425
log_level_set()
@@ -183,8 +184,9 @@ def preprocess(self) -> None:
183184
"""Preprocess an ngen run, validate some inputs, and set the execution status."""
184185

185186
# set environment variable for ngencerf backend
186-
os.environ["NGEN_RESULTS_DIR"] = str(Path(self.real_path).parent)
187-
logging.info(f"Set environment variable NGEN_RESULTS_DIR to: {os.environ['NGEN_RESULTS_DIR']}")
187+
set_os_env_key(
188+
OS_ENV_KEY_RESULTS_DIR, str(Path(self.real_path).parent), override=False
189+
)
188190

189191
# Read validation yaml file
190192
self.valid_config = load_yaml(self.valid_yaml)

python/nwm_fcst_mgr/utils.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Utilities"""
2+
3+
import logging
4+
from os import environ
5+
6+
7+
OS_ENV_KEY_RESULTS_DIR = "NGEN_RESULTS_DIR"
8+
9+
LOG = logging.getLogger(__name__)
10+
11+
12+
def set_os_env_key(key: str, val: str, override: bool = True) -> None:
13+
"""Set the value of the OS environment key.
14+
Optionally, keep the existing value for that key without overriding, if it already exists.
15+
16+
Parameters:
17+
key : str
18+
OS environment key whose value will be modified.
19+
val : str
20+
New value to set to.
21+
override : bool (default True)
22+
If True, then do replace the existing value of that key if it already exists.
23+
If False, then do not replace the value.
24+
"""
25+
errors: list[Exception] = []
26+
if not isinstance(key, str):
27+
errors.append(TypeError(f"For key {key}, expected type {str}, got {type(key)}"))
28+
if not isinstance(val, str):
29+
errors.append(
30+
TypeError(f"For value {val}, expected type {str}, got {type(val)}")
31+
)
32+
if errors:
33+
raise RuntimeError(errors)
34+
35+
if key in environ:
36+
msg_suffix = f"OS env key {repr(key)} already exists with value {repr(environ[key])}, override={override}"
37+
if not override:
38+
LOG.info("Will not override: " + msg_suffix)
39+
return
40+
LOG.info("Will override: " + msg_suffix)
41+
42+
LOG.info(f"Setting OS env key {repr(key)} to value {repr(val)}.")
43+
environ[key] = val

0 commit comments

Comments
 (0)