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