Handling indefinite paired arguments with argparse

2019-07-30 16:20发布

问题:

In my project, I need to define a syntax like

mcraw recipe add COUNT ID COUNT_1 ID_1 [COUNT_2 ID_2 ..]

and argparse seems to be the best tool for the general job.

How can I instruct Python and its argparse to construct a dictionary like this?

{
  ID_1: COUNT_1,
  ID_2: COUNT_2,
  ...
}

回答1:

Read your arguments in pairs:

argdict = {args[i + 1]: args[i] for i in xrange(0, len(args), 2)}

argparse has otherwise no special handling for this kind of input.



回答2:

I think you may have the wrong approach here. Why not point to a .json file for your program to accept on the commandline?

That way

$> python mcraw recipe add --recipies=my_recipies.json

And you can pull it in and use it however you like, possibilities include such as what is in Martijn's answer