1

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?

pjk
  • 547
  • 3
  • 14

2 Answers2

1

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

python_user
  • 5,375
  • 2
  • 13
  • 32
  • 1
    3.9 was corrected to apply the abbreviation test only to double dash strings. – hpaulj Oct 21 '20 at 14:54
  • 1
    There's fairly recent bug/issue on this, but I don't recall how well it's documented. The first introduction of `allow_abbrev` broke the long standing use of chained short options, `-vv`, `-bv` etc. – hpaulj Oct 21 '20 at 15:04
0

Don't use Single Dash. Use Double Dash. Because In single Dash(takes one single character), when you do -SS it is equivalent to -S -S that's why no error.

But if you use Double Dash then it will be

--SS => --SS
Pygirl
  • 12,969
  • 5
  • 30
  • 43