3 """Global configuration driven by commandline arguments (even across
4 different modules). Usage:
10 parser = config.add_commandline_args(
12 "Args related to module doing the thing.",
15 "--module_do_the_thing",
18 help="Should the module do the thing?"
26 parser = config.add_commandline_args(
28 "A program that does the thing.",
34 help="Should we really do the thing?"
36 config.parse() # Very important, this must be invoked!
38 If you set this up and remember to invoke config.parse(), all commandline
39 arguments will play nicely together:
43 [--module_do_the_thing MODULE_DO_THE_THING]
47 Args related to module doing the thing.
49 --module_do_the_thing MODULE_DO_THE_THING
50 Should the module do the thing?
53 A program that does the thing
56 Should we really do the thing?
58 Arguments themselves should be accessed via
59 config.config['arg_name']. e.g.
61 if not config.config['dry_run']:
72 from typing import Any, Dict, List
76 # Note: at this point in time, logging hasn't been configured and
77 # anything we log will come out the root logger.
80 class LoadFromFile(argparse.Action):
81 """Helper to load a config file into argparse."""
82 def __call__ (self, parser, namespace, values, option_string = None):
86 for line in buf.split(','):
88 line = line.strip('{')
89 line = line.strip('}')
90 m = re.match(r"^'([a-zA-Z_\-]+)'\s*:\s*(.*)$", line)
94 value = value.strip("'")
95 if value not in ('None', 'True', 'False'):
96 argv.append(f'--{key}')
98 parser.parse_args(argv, namespace)
101 # A global parser that we will collect arguments into.
102 args = argparse.ArgumentParser(
103 description=f"This program uses config.py ({__file__}) for global, cross-module configuration.",
104 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
105 fromfile_prefix_chars="@",
107 config_parse_called = False
109 # A global configuration dictionary that will contain parsed arguments
110 # It is also this variable that modules use to access parsed arguments
111 config: Dict[str, Any] = {}
113 # Defer logging messages until later when logging has been initialized.
114 saved_messages: List[str] = []
117 def add_commandline_args(title: str, description: str = ""):
118 """Create a new context for arguments and return a handle."""
119 return args.add_argument_group(title, description)
122 group = add_commandline_args(
123 f'Global Config ({__file__})',
124 'Args that control the global config itself; how meta!',
132 help='Config file from which to read args in lieu or in addition to commandline.',
138 help='Display the global configuration on STDERR at program startup.',
145 help='Populate config file compatible --config_loadfile to save config for later use.',
149 def is_flag_already_in_argv(var: str):
150 """Is a particular flag passed on the commandline?"""
157 def parse() -> Dict[str, Any]:
158 """Main program should call this early in main()"""
159 global config_parse_called
160 if config_parse_called:
162 config_parse_called = True
163 global saved_messages
165 # Examine the environment variables to settings that match
167 usage_message = args.format_usage()
170 for x in usage_message.split():
184 # Environment vars the same as flag names without
185 # the initial -'s and in UPPERCASE.
186 env = var.strip('-').upper()
187 if env in os.environ:
188 if not is_flag_already_in_argv(var):
189 value = os.environ[env]
190 saved_messages.append(
191 f'Initialized from environment: {var} = {value}'
193 if len(chunks) == 1 and string_utils.to_bool(value):
195 elif len(chunks) > 1:
197 sys.argv.append(value)
203 # Parse (possibly augmented) commandline args with argparse normally.
204 #config.update(vars(args.parse_args()))
205 known, unknown = args.parse_known_args()
206 config.update(vars(known))
208 # Reconstruct the argv with unrecognized flags for the benefit of
209 # future argument parsers.
210 sys.argv = sys.argv[:1] + unknown
212 if config['config_savefile']:
213 with open(config['config_savefile'], 'w') as wf:
214 wf.write("\n".join(sys.argv[1:]))
216 if config['config_dump']:
221 def has_been_parsed() -> bool:
222 """Has the global config been parsed yet?"""
223 global config_parse_called
224 return config_parse_called
228 """Print the current config to stdout."""
229 print("Global Configuration:", file=sys.stderr)
230 pprint.pprint(config, stream=sys.stderr)
234 """Log messages saved earlier now that logging has been initialized."""
235 logger = logging.getLogger(__name__)
236 global saved_messages
237 for _ in saved_messages: