2011-12-07 41 views
5

我的應用程序是一個專門的文件比較實用程序,顯然它只是比較一個文件沒有意義,所以nargs='+'不太合適。可以告訴python 2.7中的argparse需要至少兩個參數嗎?

nargs=N只有最多N參數除外,但只要至少有兩個參數,我需要接受無限數量的參數。

+0

也看看http://stackoverflow.com/quest離子/ 4194948 /蟒-argparse-有- - 一個單向到指定-A-範圍合NARGS。這可以提供更大的靈活性,而不會搞亂(或亂搞)幫助文本。 – Evert

回答

5

你不能做這樣的事情:

import argparse 

parser = argparse.ArgumentParser(description = "Compare files") 
parser.add_argument('first', help="the first file") 
parser.add_argument('other', nargs='+', help="the other files") 

args = parser.parse_args() 
print args 

當我跑這跟我-h得到:

usage: script.py [-h] first other [other ...] 

Compare files 

positional arguments: 
    first  the first file 
    other  the other files 

optional arguments: 
    -h, --help show this help message and exit 

當我只有一個參數運行它,它不會工作:

usage: script.py [-h] first other [other ...] 
script.py: error: too few arguments 

但是兩個或更多參數很好。隨着三個參數它打印:

Namespace(first='one', other=['two', 'three']) 
17

簡短的回答是,你不能這樣做,因爲NARGS不支持像「2+」。

龍答案是你可以變通方法,使用這樣的事情:

parser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]') 
parser.add_argument('file1', nargs=1, metavar='file') 
parser.add_argument('file2', nargs='+', metavar='file', help=argparse.SUPPRESS) 
namespace = parser.parse_args() 
namespace.file = namespace.file1 + namespace.file2 

,你需要的技巧是:

  • 使用usage你自己的使用字符串分析器提供
  • 使用metavar在幫助字符串中顯示具有不同名稱的參數
  • 使用​​,以避免對所述變量之一顯示幫助
  • 合併兩個不同的變量只是添加新屬性添加到Namespace對象解析器返回

上面的示例產生下面的幫助字符串:

usage: test.py [-h] file file [file ...] 

positional arguments: 
    file 

optional arguments: 
    -h, --help show this help message and exit 

當小於兩個參數傳遞仍然會失敗:

$ python test.py arg 
usage: test.py [-h] file file [file ...] 
test.py: error: too few arguments 
相關問題