我想做这样的事情:
usage: myprogpy [-su | -re STRING | -reg]
如何检查给出了哪些参数(su
、re
、reg
)以及 的情况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()
是否可以在方法
中分配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)
关于python - 如何在argparse中将store_true和值存储在互斥组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175255/