如何让Python Argparse只列出一次选择?

coy*_*yot 12 python argparse

我的代码看起来像:

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
Run Code Online (Sandbox Code Playgroud)

我得到的输出看起来像:

-n {foo,bar,baz}, --name {foo,bar,baz}, -o {foo,bar,baz}, 
--othername {foo,bar,baz}
Run Code Online (Sandbox Code Playgroud)

我想要的是:

-n, --name, -o, --othername {foo,bar,baz}
Run Code Online (Sandbox Code Playgroud)

对于上下文,有历史原因,为什么我们需要两个名称用于相同的选项,实际的选择列表是22个元素长,所以它看起来比上面更糟糕.

这个问题与Python argparse略有不同:许多选择导致丑陋的帮助输出,因为我没有使用两个单独的选项,并且可以将它全部放在上面这一行.

Tho*_*ltz 13

我想你可能想要多个add_arguments()并且只将选项放在你想要选择的那个上.

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)
Run Code Online (Sandbox Code Playgroud)


coy*_*yot 5

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

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

输出看起来像:

group1
   use one of -n, --name, -o, --othername
-n {foo,bar,baz}
Run Code Online (Sandbox Code Playgroud)

这比原来的要干净得多。

  • 您可以发布您拥有的代码以便我了解您在做什么吗?:) (10认同)