简体   繁体   中英

Handling indefinite paired arguments with argparse

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM