Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

python - Can argparse accept argument value as key=val pairs

I am trying to implement below option by using argparse(can't use any other tool like docopt because of project requirement):-

cli.py --conf key1=value1, key2=value2, kay3=value3
or
cli.py --conf key1=value1 key2=value2 key3=value3

So far I have tried type=json.loads or dict but not helping. One possible solution is to use type=str and then later parse it to dict. Do you guys know any other better solution which I am missing.. Thanks in advance.

Note- Can't use --key1=value1 --key2=value2 --key3=value3 because I don't want to restrict count and name of key/value. It will help in supporting new key/val in future.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you commented that you must use the cli as it is written, This is another solution. In argparse i would define the conf argument like this:

parser.add_argument('--conf', nargs='*')

With nargs='*' all the arguments following that would be in the same list which looks like this ['key1=value1', 'key2=value2', 'key3=value3']

To parse that list and get a dict out of it, you can do this:

parsed_conf = {}
for pair in conf:
    kay, value = pair.split('=')
    parsed_conf[key] = value

Now call your program like this (without commas):

cli.py --conf key1=value1 key2=value2 key3=value3

And it should work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...