Can argpse in python 2.7 require a minimum of two arguments?

My application is a specialized file comparison utility, and obviously, it makes no sense to compare only one file, so it nargs='+'doesn’t quite fit.

nargs=Nonly excludes maximum arguments N, but I need to accept an infinite number of arguments if there are at least two of them.

+5
source share
2 answers

Could you do something like this:

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

When I run this with -h, I get:

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

When I run it with only one argument, it will not work:

usage: script.py [-h] first other [other ...]
script.py: error: too few arguments

But two or more arguments are good. With three arguments, it prints:

Namespace(first='one', other=['two', 'three'])
+5
source

: , 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
+17

All Articles