2015-05-03 49 views
0

我使用这个lib中的python解析参数位置参数:https://docs.python.org/2/library/argparse.html管理多个在与argparse

到目前为止,我有这样的:

prog arg1 [-s arg2 [arg2 ...]] [-m arg3 [arg3 ...]] 

而且我想这一点:

prog arg1 -s arg2 [arg2 ...] -m arg3 [arg3 ...] 

这是我的蟒蛇码:

parser = argparse.ArgumentParser() 
parser.add_argument('path', type=str, 
        help="path used for the generation of the rouge files") 
parser.add_argument('-s', '--systems', type=str, nargs='+', 
        help="path to the systems generated summary files") 
parser.add_argument('-m', '--models', type=str, nargs='+', 
        help="path to the reference summary files") 
args = parser.parse_args() 
print args 

问题是当您调用没有可选参数的程序时,它不会给出错误(参数太少)。我希望我的可选参数是必须的,但是当你进行下面的调用,解析器不弄清楚哪种args来参与...

对于用下面的代码为例:

parser = argparse.ArgumentParser() 
parser.add_argument('arg1', type=str, nargs='+') 
parser.add_argument('arg2', type=str, nargs='+') 
parser.add_argument('arg3', type=str, nargs='+') 
args = parser.parse_args() 

而下面的调用:

python test.py arg1 arg1 arg1 arg2 arg2 arg3 arg3 

我得到这个:

Namespace(arg1=['arg1', 'arg1', 'arg1', 'arg2', 'arg2'], arg2=['arg3'], arg3=['arg3']) 

可以肯定她e是这种前卫的格式:

prog arg1 [arg1 ...] arg2 [arg2 ...] arg3 

感谢您的帮助:)

+0

什么是你的问题?这段代码是否工作? –

+0

此代码有效,但参数是可选的。我不知道如何让他们成为一种义务。 – Cadene

+0

你是什么意思的“种强制性”。 'nargs ='+''参数已经被需要。 –

回答

2

optionals可以采取required=True参数。这可能是你需要的一切。

p=argparse.ArgumentParser() 
p.add_argument('-m',nargs='+',required=True) 
p.add_argument('-n',nargs='+',required=True) 
p.print_usage() 

生产

usage: ipython3 [-h] -m M [M ...] -n N [N ...] 

至于为什么:

Namespace(arg1=['arg1', 'arg1', 'arg1', 'arg2', 'arg2'], arg2=['arg3'], arg3=['arg3']) 

您指定每个arg1, arg2, arg3需要1个或多个字符串。它将相应的长表分开,分别给出arg2arg3(满足他们的要求),其余分配给arg1。如果你熟悉regex,这相当于

In [96]: re.match('(A+)(A+)(A+)','AAAAAAAAA').groups() 
Out[96]: ('AAAAAAA', 'A', 'A') 

(解析器无法读取你的头脑和分配所有“ARG2对args2只是因为名字看起来相似。:))

所以,如果你需要以特定的方式分割参数列表,然后optionals(标志)是要走的路。而在nargsrequired之间,你对数字有相当的控制权。

+0

谢谢你现在可以工作;) – Cadene

1

你想要什么是不可能的。想一想:如果你要实现自己的参数解析而没有​​,你如何确定一个位置参数是arg1参数列表中的最后一个,还是第一个arg2参数?

我认为你已经知道的解决方案(可选参数)工作正常,甚至更好。

0

我需要添加=真和它的作品,这要归功于hpaulj

parser = argparse.ArgumentParser() 
parser.add_argument('path', type=str, 
        help="path used for the generation of the rouge files") 
parser.add_argument('-s', '--systems', type=str, nargs='+', required=True, 
        help="path to the systems generated summary files") 
parser.add_argument('-m', '--models', type=str, nargs='+', required=True, 
        help="path to the reference summary files") 
args = parser.parse_args() 

python summary2rouge.py 
usage: summary2rouge.py [-h] -s SYSTEMS [SYSTEMS ...] -m MODELS [MODELS ...] 
        path 
summary2rouge.py: error: too few arguments