【问题标题】:Can argparse in python 2.7 be told to require a minimum of TWO arguments?可以告诉 python 2.7 中的 argparse 至少需要两个参数吗?
【发布时间】:2011-12-07 06:22:31
【问题描述】:

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

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

【问题讨论】:

标签: python argparse


【解决方案1】:

简短的回答是你不能这样做,因为 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

你需要的技巧是:

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

上面的例子产生了以下帮助字符串:

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

【讨论】:

    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2017-01-15
      • 2021-07-07
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2014-12-14
      • 1970-01-01
      相关资源
      最近更新 更多