python - 如何在argparse中将store_true和值存储在互斥组中?

标签 python arguments 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()

是否可以在方法中分配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/

相关文章:

python - ModuleNotFoundError : No module named 'pyinputplus'

python - (Un)多组复选按钮的全选复选按钮功能

python - 对基于 'if' 的列表元素进行子集化

arrays - 将参数和数组的组合从 linux shell 脚本传递到另一个 shell 脚本

php - 如何将 PHP 函数的参数列表转换为关联数组?

javascript - 重用传递给 .apply() 的数组是否安全?

python - 使用 argparse 参数作为关键字参数

python - 如何应用一个接收两个参数作为 Pandas 列的函数?

python - 如何在 Python 的 argparse 中对同一组参数调用 parse_args() 两次?

python - argparse 其他参数隐含的子解析器