2

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.

AlokThakur
  • 3,599
  • 1
  • 19
  • 32
  • Why not use multiple arguments for `key1` and `key2` etc.? – Ofer Sadan Jul 11 '17 at 04:36
  • Didn't you ask for this, [Using argparse to parse arguments of form “arg= val”](https://stackoverflow.com/questions/5154716/using-argparse-to-parse-arguments-of-form-arg-val). This seems to be helpful to you. – arif Jul 11 '17 at 04:39
  • do you have a constant number of key value pairs? if so, as @OferSadan mentioned, you can just pass them like this `--key1=value1 --key2=value2 --key3=value3` – otayeby Jul 11 '17 at 04:39
  • 1. There would be other arguments as well, don't want to give option to use key1 and key2 with any other argument 2. Dont want to restrict count and name of key/value pair, If new key/value need to be supported then no changes would be needed in argument parser – AlokThakur Jul 11 '17 at 04:39
  • @AlokThakur Please mention those two assumptions in your question to avoid duplication. – otayeby Jul 11 '17 at 04:41
  • @tiba sorry for confusion, updated question – AlokThakur Jul 11 '17 at 04:45

2 Answers2

5

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

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
2

I would use type=str and parse it later, perhaps with json, but the main problem with that would be the way you are writing your command:

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

The spaces split each pair to a different argument. If you use either method you suggested it would not work. Instead make sure that they are all one argument:

cli.py --conf="key1='value1', key2='value2', kay3='value3'"

That way this large argument is ready to be parsed as json

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62