Setting options from environment variables when using argparse

后端 未结 12 2011
执念已碎
执念已碎 2020-12-08 04:06

I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, a

12条回答
  •  执念已碎
    2020-12-08 04:33

    The topic is quite old, but I had similar problem and I thought I would share my solution with you. Unfortunately custom action solution suggested by @Russell Heilling doesn't work for me for couple of reasons:

    • It prevents me from using predefined actions (like store_true)
    • I would rather like it to fallback to default when envvar is not in os.environ (that could be easily fixed)
    • I would like to have this behaviour for all of my arguments without specifying action or envvar (which should always be action.dest.upper())

    Here's my solution (in Python 3):

    class CustomArgumentParser(argparse.ArgumentParser):
        class _CustomHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
            def _get_help_string(self, action):
                help = super()._get_help_string(action)
                if action.dest != 'help':
                    help += ' [env: {}]'.format(action.dest.upper())
                return help
    
        def __init__(self, *, formatter_class=_CustomHelpFormatter, **kwargs):
            super().__init__(formatter_class=formatter_class, **kwargs)
    
        def _add_action(self, action):
            action.default = os.environ.get(action.dest.upper(), action.default)
            return super()._add_action(action)
    

提交回复
热议问题