Ask for 0 or 2 positional arguments with argparse?
Question:
I’m learning argparse module and I want to ask 0 or 2 files.
parser.add_argument("infile", nargs = {0,2}, type=argparse.FileType('r'))
It should work with :
python prog.py
python prog.py infile1 infile2
But not with :
python prog.py infile1
python prog.py infile1 infile2 infile3
Actually I use 2 different arguments with "nargs=’?’ and I test
sys.argv == 1 or sys.argv == 3
Answers:
I wanted this once, and found that argparse
doesn’t support it natively, so I wrote it like this.
#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b]n')
parser.add_argument('ab',
nargs='*',
help='specify 2 or 0 items',
default=['a', 'b'])
args = parser.parse_args()
if len(args.ab) != 2:
parser.error('expected 2 arguments')
print(args.ab)
Note over-riding the usage message when you create the parser, because the default usage message will be misleading otherwise.
I had the same use case, and wim’s answer works. Here is the documentation for usage
in the Python argparse docs in case anyone needs it. This will customize the output of the help message.
I’m learning argparse module and I want to ask 0 or 2 files.
parser.add_argument("infile", nargs = {0,2}, type=argparse.FileType('r'))
It should work with :
python prog.py
python prog.py infile1 infile2
But not with :
python prog.py infile1
python prog.py infile1 infile2 infile3
Actually I use 2 different arguments with "nargs=’?’ and I test
sys.argv == 1 or sys.argv == 3
I wanted this once, and found that argparse
doesn’t support it natively, so I wrote it like this.
#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b]n')
parser.add_argument('ab',
nargs='*',
help='specify 2 or 0 items',
default=['a', 'b'])
args = parser.parse_args()
if len(args.ab) != 2:
parser.error('expected 2 arguments')
print(args.ab)
Note over-riding the usage message when you create the parser, because the default usage message will be misleading otherwise.
I had the same use case, and wim’s answer works. Here is the documentation for usage
in the Python argparse docs in case anyone needs it. This will customize the output of the help message.