I am working on a Python script using argparse
library to handle command-line arguments. I want to enforce strict and case sensitive match for a specific flag. such as --signup
, without allowing any other variations, shorthand or incorrect spellings and any value afterwards.
I have tried using a custom action along with the nargs
parameter, but I'm facing challenges to achieve desired outcome. Here is simplified version of my code:
import argparse
class ValidateSignupAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None) -> None:
if values != ['--signup']:
parser.print_help()
parser.exit(1)
setattr(namespace, self.dest, values)
def register_args():
parser = argparse.ArgumentParser()
parser.add_argument("--signup", action=ValidateSignupAction, help="Initiate user signup process", required=True)
register_args = parser.parse_args()
return register_args
Code is not producing the desired outcome. When I provide command python register.py --signup
or python register.py --singup
, It prints the help menu for both command-lines. I want it to return True
if python register.py --signup
without any value after --signup
.
Running this script:
> python .\register.py --signup
Prints:
usage: register.py [-h] --signup SIGNUP
register.py: error: argument --signup: expected one argument
Is there a way to achieve this level of strict match for the --signup
flag using argparse
alone? Or should I consider an alternative approach?
Any suggestion or guidance would be greatly helpful. Thankyou in Advance for you help.
Additional Notes:
I have tried using choices
parameter, but it does not seem to work for my use case.
I am aiming to enforce the exact flag with no shorthand or variations, even in different letter cases.
Testing in an ipython session:
In [128]: parser = argparse.ArgumentParser(allow_abbrev=False)
In [129]: parser.add_argument('--signup', action='store_true');
Correct use:
In [130]: parser.parse_args('--signup'.split())
Out[130]: Namespace(signup=True)
attempting to add a string
In [131]: parser.parse_args('--signup foobar'.split())
usage: ipython [-h] [--signup]
ipython: error: unrecognized arguments: foobar
SystemExit: 2
attempting an abbreviation:
In [132]: parser.parse_args('--sign'.split())
usage: ipython [-h] [--signup]
ipython: error: unrecognized arguments: --sign
SystemExit: 2