如何解决如何在Python3中使用argparse解析两组命令行参数中的一组?
我想开发一个将两对参数之一结合在一起的CLI:
group-resources --limit 5
或
group-overlap --groups group1,group2
group-resources是位置信息,必须有限制。其余两个规则相同。 但是,根据我当前的代码,所有这四个条件都是强制性的。
我当前的代码:
import argparse
import analysis
import cleanup
import etl
import initialize_db
parser = argparse.ArgumentParser(
description='Inventory DB for Cloud Infrastructure')
parser.add_argument(
'group-resources',help='List top k groups as per their memory,disk,and cpu count.')
parser.add_argument(
'--limit',help='Number of groups in descending order of their resources.',type=int,required=True)
parser.add_argument(
'group-overlap',help='Fetch nodes that belong in both the groups')
parser.add_argument(
'--groups',help='specify the group names separated by a comma.',type=str,required=True
)
args = parser.parse_args()
print(args)
运行python3 cli.py group-resources --limit 5
时,出现以下错误:
usage: cli.py [-h] --limit LIMIT --groups GROUPS group-resources group-overlap
cli.py: error: the following arguments are required: group-overlap,--groups
我希望如果我提供组资源和限制,或者提供组重叠和组,那么我的代码应该可以工作。不允许其他排列。我该怎么办?
解决方法
我们可以使用subparsers。这是我们可以在您的代码中稍加修改的方法。
import argparse
parser = argparse.ArgumentParser(
description='Inventory DB for Cloud Infrastructure')
subparsers = parser.add_subparsers(help='types of arguments')
group_resources_parser = subparsers.add_parser("group-resources",help='List top k groups as per their memory,disk,and cpu count.')
group_overlap_parser = subparsers.add_parser("group-overlap",help='Fetch nodes that belong in both the groups')
group_resources_parser.add_argument(
'--limit',help='Number of groups in descending order of their resources.',type=int,required=True)
group_overlap_parser.add_argument(
'--groups',help='specify the group names separated by a comma.',type=str,required=True
)
args = parser.parse_args()
print(args)
示例:
-
python3 cli.py组资源
usage: cli.py group-resources [-h] --limit LIMIT cli.py group-resources: error: the following arguments are required: --limit
-
python3 cli.py组重叠
usage: cli.py group-overlap [-h] --groups GROUPS cli.py group-overlap: error: the following arguments are required: --groups
-
python3 cli.py group-resources --limit 5 group-overlap
usage: cli.py [-h] {group-resources,group-overlap} ... cli.py: error: unrecognized arguments: group-overlap
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。