能否告知python 2.7中的argparse至少需要两个参数? [英] Can argparse in python 2.7 be told to require a minimum of TWO arguments?
问题描述
我的应用程序是一种专用的文件比较实用程序,显然只比较一个文件没有意义,所以nargs='+'
不太合适.
My application is a specialized file comparison utility and obviously it does not make sense to compare only one file, so nargs='+'
is not quite appropriate.
nargs=N
仅允许最多N
个参数,但是只要有至少两个参数,我就需要接受无限数量的参数.
nargs=N
only excepts a maximum of N
arguments, but I need to accept an infinite number of arguments as long as there are at least two of them.
推荐答案
简短的答案是您不能这样做,因为nargs不支持"2+"之类的东西.
Short answer is you can't do that because nargs doesn't support something like '2+'.
长答案是您可以使用以下方法解决此问题:
Long answer is you can workaround that using something like this:
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
对象添加新属性
- Use
usage
to provide you own usage string to the parser - Use
metavar
to display an argument with a different name in the help string - Use
SUPPRESS
to avoid displaying help for one of the variables - Merge two different variables just adding a new attribute to the
Namespace
object that the parser returns
上面的示例产生以下帮助字符串:
The example above produces the following help string:
usage: test.py [-h] file file [file ...]
positional arguments:
file
optional arguments:
-h, --help show this help message and exit
,并且在传递少于两个参数时仍然会失败:
and will still fail when less than two arguments are passed:
$ python test.py arg
usage: test.py [-h] file file [file ...]
test.py: error: too few arguments
这篇关于能否告知python 2.7中的argparse至少需要两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!