简体   繁体   English

如何在argparse的互斥组中存储_true和存储值?

[英]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?我如何检查给出了哪些参数( surereg ),并且在re的情况下,获取给定的字符串?

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?是否可以在method分配true/false值,以及将字符串存储在不同的变量中? Is there another way?还有其他方法吗?

Use the (default) 'store' and 'store_const' actions, not 'store_true' .使用(默认) 'store''store_const'操作,而不是'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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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