简体   繁体   中英

How to store_true and store value in a mutual exclusive group in argparse?

I want to do something like this:

usage: myprogpy [-su | -re STRING | -reg]

How do I check which of the arguments were given ( su , re , reg ), and in the case of re , obtain the given string?

ap = argparse.ArgumentParser(prog="myprog.py")
    method_group = ap.add_mutually_exclusive_group()
    method_group.add_argument('-su', '--speedup', action='store_true', dest='method')
    method_group.add_argument('-re', '--relative', action='store_true', dest='method')
    method_group.add_argument('-reg', '--regular', action='store_true', dest='method')
    args = ap.parse_args()

    if args.method == "speedup":
        speedup()

    elif args.method == "relative":
        relative(string_value) # How do I get the string value???

    elif args.method == "regular":
        regular()

Is it possible to get assign true/false value in method , as well as storing the string in a different variable? Is there another way?

Use the (default) 'store' and 'store_const' actions, not 'store_true' .

ap = argparse.ArgumentParser(prog="myprog.py")
method_group = ap.add_mutually_exclusive_group()
method_group.add_argument('-su', '--speedup',
                          action='store_const',
                          const='speedup',
                          dest='method')
method_group.add_argument('-re', '--relative',
                          dest='method')
method_group.add_argument('-reg', '--regular',
                          action='store_const',
                          const='regular',
                          dest='method')
args = ap.parse_args()

if args.method == "speedup":
    speedup()
elif args.method == "regular":
    regular()
elif args.method is not None:
    relative(args.method)

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