【问题标题】:How can I get Python Argparse to list choices only once?如何让 Python Argparse 仅列出一次选择?
【发布时间】:2020-01-23 04:01:39
【问题描述】:

我的代码如下所示:

list_of_choices = ["foo", "bar", "baz"]
parser = argparse.ArgumentParser(description='some description')
parser.add_argument("-n","--name","-o","--othername",dest=name,
    choices=list_of_choices

我得到的输出如下:

-n {foo,bar,baz}, --name {foo,bar,baz}, -o {foo,bar,baz}, 
--othername {foo,bar,baz}

我想要的是:

-n, --name, -o, --othername {foo,bar,baz}

就上下文而言,我们需要为同一个选项提供两个名称是有历史原因的,而实际的选项列表有 22 个元素长,所以看起来比上面的要糟糕得多。

这个问题与Python argparse: Lots of choices results in ugly help output 有细微的不同,因为我没有使用两个单独的选项,并且可以像上面那样将它们全部放在一起。

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    我认为您可能想要多个add_arguments(),并且只在您想要选择的那个上设置choices

    list_of_choices = ["foo", "bar", "baz"]
    parser = argparse.ArgumentParser(description='some description')
    parser.add_argument("-n")
    parser.add_argument("--name")
    parser.add_argument("-o")
    parser.add_argument("--othername", dest='name',
        choices=list_of_choices)
    

    【讨论】:

    • 我不认为这很有效,因为如果我通过 -f foo,我稍后会收到一个错误,说 name 是 None。
    • 您是要捕捉所有参数还是只接受您定义的参数?在这种情况下,您必须为 -f 执行另一个 add_argument()。我也认为 dest 应该是一个字符串 dest='name'。 docs.python.org/dev/library/argparse.html#dest
    【解决方案2】:

    谢谢,@thomas-schultz。我不知道 add_argument 的顺序方面,您的评论使我走上了正确的轨道,并结合了来自其他线程的评论。

    基本上,我现在所做的是将所有四个放在一个互斥组中,抑制前三个的输出,然后将它们包含在组的描述中。

    输出如下:

    group1
       use one of -n, --name, -o, --othername
    -n {foo,bar,baz}
    

    比原版干净得多。

    【讨论】:

    • 你能把你的代码贴出来让我知道你在做什么吗? :)
    【解决方案3】:

    这是我经过更多调整后确定的代码:

    parser = argparse.ArgumentParser(description='some description', 
        epilog="At least one of -n, -o, --name, or --othername is required"
               " and they all do the same thing.") 
    parser.add_argument('-d', '--dummy', dest='dummy',
        default=None, help='some other flag')
    stuff = parser.add_mutually_exclusive_group(required=True)
    stuff.add_argument('-n', dest='name', 
        action='store', choices=all_grids, help=argparse.SUPPRESS)
    stuff.add_argument('-o', dest='name', 
        action='store', choices=all_grids, help=argparse.SUPPRESS)
    stuff.add_argument('--name', dest='name', 
        action='store', choices=all_grids, help=argparse.SUPPRESS)
    stuff.add_argument('--othername', dest='name', 
        action='store', choices=all_grids, help='')
    args = parser.parse_args()
    

    -h 的输出是用法,然后是选项列表,然后是:

    --othername {foo,bar,baz}
    
    At least one of -n, -o, --name, or --othername is required and they all do the same thing.
    

    【讨论】:

    • 为什么不将此编辑到您的其他答案中?毕竟,这是同一个答案的一部分。
    • 另外,action='store' is the default 可以省略。
    猜你喜欢
    • 2018-07-20
    • 2017-04-02
    • 2014-02-03
    • 2018-04-08
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多