简体   繁体   中英

Using JSON with argparse & store_true in python

So I've got everything working just fine with it, other than one argument I have. My goal is to pull all the arguments from the JSON file. Almost all my arguments are something along the lines of this.

"-lc",
"--lower",
type=int,
default=1,
dest="min_lowercase",
help="Minimum number of lowercase alpha characters")

but I do have one boolean toggle argument which is:

"-ext",
"--extended",
action="store_const",
default=False,
const=True,
dest="special_extended",
help="Toggles the extended special character subset. Passwords may not be accepted by all services")

I've tried tons of different things and I just can't get a JSON format that works for all of them & and an input method that inputs properly. Here's roughly what I've been using for inputting, with slight adjusts depending on the method I've tried to get it to work.

with open("a.json") as f:
    data = json.load(f)
for item in data:
    parser.add_argument(
        item["short_arg"],
        item["long_arg"],
        type=eval(item["type"]),
        default=item["default"],
        dest=item["dest"],
        help=item["help"],
    )

You can use **kwargs concept, then you don't need to design your own JSON format. Only thing you need to ensure is that it is serialisable. For this, store as string then as per your code convert to an object

from argparse import ArgumentParser as ArgParser
import json

if __name__ == '__main__':
    description = ('Example')
    parser = ArgParser(description=description)
    allargs = [{"name":"--env", "kwargs":{"default":"", "type":"str", "help":'env to build - all if not specified'}},
                {"name": "--param2", "kwargs":{"default":2, "type":"int", "help":'default 2'}}
                ]
    print(json.dumps(allargs))
    for arg in allargs:
        arg["kwargs"]["type"] = eval(arg["kwargs"]["type"])
        parser.add_argument(arg["name"], **arg["kwargs"])
    options = parser.parse_args()
    print(options)

output

[{"name": "--env", "kwargs": {"default": "", "type": "str", "help": "env to build - all if not specified"}}, {"name": "--param2", "kwargs": {"default": 2, "type": "int", "help": "default 2"}}]
Namespace(env='', param2=2)

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