簡體   English   中英

如何在argparse的互斥組中存儲_true和存儲值?

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

我想做這樣的事情:

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

我如何檢查給出了哪些參數( 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()

是否可以在method分配true/false值,以及將字符串存儲在不同的變量中? 還有其他方法嗎?

使用(默認) '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