Python argparse dict arg

前端 未结 9 1695
不知归路
不知归路 2021-02-01 04:31

I want to receive a dict(str -> str) argument from the command line. Does argparse.ArgumentParser provide it? Or any other library?

For the

9条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 04:38

    As for the current libraries like argparse, docopt and click, none of them support using dict args. The best solution I can think of is to make a custom argparse.Action to support it youself:

    import argparse
    
    class MyAction(argparse.Action):
        def __init__(self, option_strings, dest, nargs=None, **kwargs):
            super(MyAction, self).__init__(option_strings, dest, nargs, **kwargs)
    
        def __call__(self, parser, namespace, values, option_string=None):
            print '%r %r %r' % (namespace, values, option_string)
            value_dict = {}
            values.reverse()
            while len(values) > 0:
                v = eval(values.pop()).lstrip('--') # This is like crazy hack, I know.
                k = eval(values.pop())
                value_dict[k] = v
    
            setattr(namespace, self.dest, value_dict)
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', action=MyAction, nargs='*')
    args = parser.parse_args('-d "--key" "key1" "--value" "val1" "--key" "key2" "--value" "val2"'.split())
    
    print(args)
    

提交回复
热议问题