+ global saved_messages
+
+ # If we're about to do the usage message dump, put the main module's
+ # argument group first in the list (if possible), please.
+ reordered_action_groups = []
+ prog = sys.argv[0]
+
+ for arg in sys.argv:
+ if arg == '--help' or arg == '-h':
+ for group in args._action_groups:
+ if entry_module is not None and entry_module in group.title:
+ reordered_action_groups.insert(0, group) # prepend
+ elif prog in group.title:
+ reordered_action_groups.insert(0, group) # prepend
+ else:
+ reordered_action_groups.append(group) # append
+ args._action_groups = reordered_action_groups
+
+ # Examine the environment variables to settings that match
+ # known flags. For a flag called --example_flag the corresponding
+ # environment variable would be called EXAMPLE_FLAG.
+ usage_message = args.format_usage()
+ optional = False
+ var = ''
+ for x in usage_message.split():
+ if x[0] == '[':
+ optional = True
+ if optional:
+ var += f'{x} '
+ if x[-1] == ']':
+ optional = False
+ var = var.strip()
+ var = var.strip('[')
+ var = var.strip(']')
+ chunks = var.split()
+ if len(chunks) > 1:
+ var = var.split()[0]
+
+ # Environment vars the same as flag names without
+ # the initial -'s and in UPPERCASE.
+ env = var.strip('-').upper()
+ if env in os.environ:
+ if not is_flag_already_in_argv(var):
+ value = os.environ[env]
+ saved_messages.append(
+ f'Initialized from environment: {var} = {value}'
+ )
+ from string_utils import to_bool
+ if len(chunks) == 1 and to_bool(value):
+ sys.argv.append(var)
+ elif len(chunks) > 1:
+ sys.argv.append(var)
+ sys.argv.append(value)
+ var = ''
+ env = ''
+ else:
+ next
+
+ # Parse (possibly augmented) commandline args with argparse normally.
+ known, unknown = args.parse_known_args()
+ config.update(vars(known))
+
+ # Reconstruct the argv with unrecognized flags for the benefit of
+ # future argument parsers. For example, unittest_main in python
+ # has some of its own flags. If we didn't recognize it, maybe
+ # someone else will.
+ sys.argv = sys.argv[:1] + unknown