可以告诉python 2.7中的argparse需要至少两个参数吗?

Bry*_*phy 5 python argparse

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

nargs=N只排除最多的N参数,但只要至少有两个参数,我需要接受无数个参数.

jco*_*ado 18

简短的回答是你不能这样做,因为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
Run Code Online (Sandbox Code Playgroud)

你需要的技巧是:

  • 用于usage为解析器提供自己的使用字符串
  • 用于metavar在帮助字符串中显示具有不同名称的参数
  • 使用SUPPRESS以避免显示帮助的一个变量
  • 合并两个不同的变量,只需向Namespace解析器返回的对象添加新属性即可

上面的示例生成以下帮助字符串:

usage: test.py [-h] file file [file ...]

positional arguments:
  file

optional arguments:
  -h, --help  show this help message and exit
Run Code Online (Sandbox Code Playgroud)

当传递少于两个参数时仍然会失败:

$ python test.py arg
usage: test.py [-h] file file [file ...]
test.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)


srg*_*erg 6

你不能做这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,-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
Run Code Online (Sandbox Code Playgroud)

当我只使用一个参数运行它时,它将无法工作:

usage: script.py [-h] first other [other ...]
script.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)

但是两个或多个论点都没问题.打印出三个参数:

Namespace(first='one', other=['two', 'three'])
Run Code Online (Sandbox Code Playgroud)