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

查看:28
本文介绍了可以告诉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天全站免登陆