Skip to content
Advertisement

Command line args accepting -SS also where as expected is -S using argparse

I have command line argument -S as defined below

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
        '-S',
        '--save',
        action='store_true',
        help='Save to directory'
    )

but if I use -SS instead of -S, python doesn’t throw any error. I want invalid argument error. Can anybody tell me how to achieve this?

Advertisement

Answer

You need to use allow_abbrev=False in argparse.ArgumentParse

import argparse
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('-S',action='store_true',help='Save to directory')
parser.parse_args()

Output:

user@localhost:/tmp$ python3 temp.py -S
user@localhost:/tmp$ python3 temp.py -SS
usage: temp.py [-h] [-S]
temp.py: error: unrecognized arguments: -SS

Error is raised when it is called with -SS

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement