能否告知python 2.7中的argparse至少需要两个参数? [英] Can argparse in python 2.7 be told to require a minimum of TWO arguments?

查看:112
本文介绍了能否告知python 2.7中的argparse至少需要两个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是一种专用的文件比较实用程序,显然只比较一个文件没有意义,所以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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆