문제

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.

Python Argparse Documentation - Usage

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top