【问题标题】:How to parse one group out of the two groups of command line arguments using argparse in Python3?如何在 Python3 中使用 argparse 从两组命令行参数中解析出一组?
【发布时间】:2021-01-12 23:23:48
【问题描述】:

我想开发一个 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

我希望如果我提供组资源和限制,或者如果我提供组重叠和组,那么我的代码应该可以工作。不应允许其他排列。我该怎么做?

【问题讨论】:

    标签: python python-3.x command-line-interface argparse


    【解决方案1】:

    我们可以使用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)
    

    示例:

    1. python3 cli.py 组资源

        usage: cli.py group-resources [-h] --limit LIMIT
        cli.py group-resources: error: the following arguments are required: --limit
      
    2. python3 cli.py 组重叠

       usage: cli.py group-overlap [-h] --groups GROUPS
       cli.py group-overlap: error: the following arguments are required: --groups
      
    3. python3 cli.py group-resources --limit 5 group-overlap

        usage: cli.py [-h] {group-resources,group-overlap} ...
        cli.py: error: unrecognized arguments: group-overlap
      

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 1970-01-01
      • 2014-07-10
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      相关资源
      最近更新 更多