2012-11-20 71 views
9

我有如下所示的代码:我怎样才能让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 

和我所得到的输出如下:

-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略有不同,因为我没有使用两个单独的选项,并且可以将它全部放在上面。

回答

8

我想你可能要多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) 
+0

我不认为这很有效,因为如果我通过-f foo的,后来我得到一个错误说的名字是无。 – coyot

+0

你是想抓住所有参数还是只接受你定义的参数?在这种情况下,你必须为-f做另一个add_argument()。另外我认为dest应该是一个字符串dest ='name'。 http://docs.python.org/dev/library/argparse.html#dest –

3

谢谢,@ thomas-schultz。我不知道add_argument的顺序方面和你的评论让我在正确的轨道上,加上从其他线程的注释。

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

输出看起来像:

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

这是更比原来干净。

+7

你能后你有这样的代码,我明白你在做什么? :) –

0

下面是我多一点的调整后,定居的代码,太大评论:(

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() 

输出如下:

(使用情况,然后选项列表,然后:)

--othername {FOO,酒吧,巴兹}

至少-n之一,-o,--name或--othername是必需的,他们都做同样的事情。

+0

为什么不编辑这个到你的其他答案?毕竟,这是同一个答案的一部分。 – Michael