File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1919from nwm_fcst_mgr .log_level import log_level_set
2020from nwm_fcst_mgr .git_util import print_git_info_all
2121from 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
2425log_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 )
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments