【发布时间】:2011-12-07 06:22:31
【问题描述】:
我的应用程序是一个专门的文件比较实用程序,显然只比较一个文件是没有意义的,所以nargs='+' 不太合适。
nargs=N 仅排除最多 N 参数,但只要至少有两个参数,我就需要接受无限数量的参数。
【问题讨论】:
-
也看看stackoverflow.com/questions/4194948/…。这样可以提供更大的灵活性,而不会弄乱(或弄乱)帮助文本。
我的应用程序是一个专门的文件比较实用程序,显然只比较一个文件是没有意义的,所以nargs='+' 不太合适。
nargs=N 仅排除最多 N 参数,但只要至少有两个参数,我就需要接受无限数量的参数。
【问题讨论】:
简短的回答是你不能这样做,因为 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 在帮助字符串中显示具有不同名称的参数SUPPRESS 避免显示变量之一的帮助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
【讨论】:
你不能这样做吗:
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'])
【讨论】: