Using argparse to parse arguments of form “arg= val”

后端 未结 4 1432
时光说笑
时光说笑 2020-12-14 18:20

I want to use argparse to parse command lines of form \"arg=val\" For example, the usage would be:

script.py conf_dir=/tmp/good_conf

To ach

4条回答
  •  暖寄归人
    2020-12-14 18:49

    @chepner This is great. I improved this to support multiple args as well and store the result as dict:

    class StoreDict(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            kv={}
            if not isinstance(values, (list,)):
                values=(values,)
            for value in values:
                n, v = value.split('=')
                kv[n]=v
            setattr(namespace, self.dest, kv)
    

提交回复
热议问题