ConfigArgParse icon indicating copy to clipboard operation
ConfigArgParse copied to clipboard

Parse yaml directories as key=value pairs

Open katharinahafner opened this issue 3 years ago • 2 comments

Fix #258

katharinahafner avatar Jun 07 '22 09:06 katharinahafner

Minimal example:

# config.yml
vars:
  a: [1, 2, 3]
  b: "foo"
  c: "bar"

Add an action to parse dict-string to dict

import argparse
from configargparse import ArgParser, YAMLConfigFileParser

class StoreDict(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        import json
        try:
            my_dict = json.loads(values)
        except json.JSONDecodeError:
            my_dict = json.loads(values.replace("'",'"'))
        setattr(namespace, self.dest, my_dict)

p = ArgParser(config_file_parser_class=YAMLConfigFileParser)
p.add('-c', '--config_file', default='config.yml', is_config_file=True)
p.add('--vars', dest="vars", action=StoreDict)
args = p.parse_args()

print(args.vars)
Output: {'a': [1, 2, 3], 'b': 'foo', 'c': 'bar'}

katharinahafner avatar Jun 07 '22 12:06 katharinahafner

If other users would like to see support for dictionaries, please post your views here or in https://github.com/bw2/ConfigArgParse/issues/258

bw2 avatar Jun 27 '23 19:06 bw2