Handling indefinite paired arguments with argparse

2019-07-30 16:26发布

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,
  ...
}

2条回答
霸刀☆藐视天下
2楼-- · 2019-07-30 16:43

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.

查看更多
神经病院院长
3楼-- · 2019-07-30 16:45

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

查看更多
登录 后发表回答