python - 如何避免在 python 中使用特定的可选参数

标签 python argparse

大家好,我正在努力在 python 中创建帮助菜单。下面是代码。

__author__ = 'akthakur'
import argparse
import database_helper
import sys
import database_operations_full
import withoutTransactionaldata
print("Database Backup and restoration Application".center(60,'*'))
parser = argparse.ArgumentParser(description="My database backup application")
group = parser.add_mutually_exclusive_group()
group.add_argument("-g","--group",type=str,help="defines database    groups",default='nothing')
group.add_argument("-a","--all",help="backup all   databases",action="store_true")
group.add_argument("-d","--databases",nargs='+',help="take multiple databases as input",default=[])
parser.add_argument("-r","--reference",help="backups reference data-only",action="store_true")

假设我在上面编写的代码的Python文件的名称是test.py 所以下面的操作应该抛出错误

python test.py -r

我没有人单独使用 -r 选项来调用我的应用程序。如果必须使用 -r,那么他还必须使用 -a 或 -d 或 -g

最佳答案

如果他们总是必须指定 -a 、 -d 、 -g 之一,则使用 add_mutually_exclusive_group(required=True)

如果他们只需要在指定 -r 时执行此操作,您将需要一个 if 语句,例如:

args = parser.parse_args()
if args.reference:
    if not args.databases and not args.all and args.group == 'nothing':
        parser.error("Must specify -a, -d, or -g with -r")

关于python - 如何避免在 python 中使用特定的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812325/

相关文章:

python - 通过 opencv 和 python 实时跟踪对象

python - Windows 中的 PySide - 从角落移除填充

python - 如何在 pymongo 中否定正则表达式

python - 没有破折号但带有附加参数的可选 python 参数?

Python argparse - 如果没有给出参数,则默认互斥组

python - 使用 np.where 在 matplotlib 中按类别着色

python - 我必须归档,并且需要根据文件 AddValueHere 的日期填补文件 LookupHere 的空白

python - 覆盖 argparse -h 行为第 2 部分

python - argparse.ArgumentParser() 函数的描述参数

python - 使用 argparse 从命令行获取自定义结构列表