1

I have the following script which simply parses arguments passed in commandline

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='My test script')
    parser.add_argument('-somearg', dest='somearg', type=str, required=True, help='Help yourself')
    parser.add_argument("-somemorearg", dest='somemorearg', action='store_true', help='Help yourself')   # Treated as boolean if passed in
    parser.add_argument("-somemoreargagain", dest='somemoreargagain', action='store_true', help='Help yourself') # Treated as boolean if passed in
    args = parser.parse_args()

    print('Your input was:         ' + args.somearg)
    if args.somemorearg == True:
        print('Second parameter is true: ')
    if args.somemoreargagain == True:
        print('Second parameter is true: ')

Following is the way I call the script which works:

python my_script.py -somearg xyz -somemorearg -somemoreargagain

Above is great!
But if I call my script with a slight typo like below, that works as well? That is strange behaviour from python! Note that in the below call, I am missing the n in last parameter which should be somemoreargagain

python my_script.py -somearg xyz -somemorearg -somemoreargagai

Is above behaviour default in python as it looks like? I want to make the script stringent in parameter checks.

How can I make the script throw an error if parameters passed in dont match accurately? I want my script to only accept -somearg, -somemorearg and -somemorearg

I am using Python 3+

TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159
  • Please have a look at https://stackoverflow.com/questions/12818146/python-argparse-ignore-unrecognised-arguments – kraymer Nov 23 '20 at 13:48
  • 1
    Please note my question is "How can I make the script throw an error if the criteria does not match?" – TheWaterProgrammer Nov 23 '20 at 14:04
  • 1
    `allow_abbrev` parameter was added recently to give you control over its handing of abbreviations. But you could also choose argument flags that are sufficiently different (and short) that this kind of error is impossible. Your lazy users will thank you for it. – hpaulj Nov 23 '20 at 16:59

1 Answers1

2

using partial argument names works with argparse as long as it is long enough to be unique for only one parameter. the same wouldn't work if you typed python my_script.py -somearg xyz -somemorear since -somemorear would be an ambiguous name for 2 parameters

AntiMatterDynamite
  • 1,495
  • 7
  • 17