Python2.7中的argparse是否至少需要两个参数?

Python2.7中的argparse是否至少需要两个参数?,python,argparse,Python,Argparse,我的应用程序是一个专门的文件比较实用程序,显然只比较一个文件没有意义,因此nargs='+'不太合适 nargs=N最多只能接受N个参数,但我需要接受无限多个参数,只要至少有两个参数。你不能这样做吗: import argparse parser = argparse.ArgumentParser(description = "Compare files") parser.add_argument('first', help="the first file") parser.add_argum

我的应用程序是一个专门的文件比较实用程序,显然只比较一个文件没有意义,因此
nargs='+'
不太合适


nargs=N
最多只能接受
N
个参数,但我需要接受无限多个参数,只要至少有两个参数。

你不能这样做吗:

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
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
当我使用
-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'])

简而言之,你不能这么做,因为NARG不支持像“2+”这样的东西

长话短说,您可以通过以下方式解决这一问题:

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
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
    避免显示其中一个变量的帮助
  • 合并两个不同的变量,只需向解析器返回的
    名称空间
    对象添加一个新属性
上面的示例生成以下帮助字符串:

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
也来看看。这允许更大的灵活性,而不会弄乱(或干扰)帮助文本。