import argparse parser = argparse.ArgumentParser() parser.add_argument('somearg', help='Some argument') args = parser.parse_args() parameter = args.somearg print("You provided parameter {}!".format(parameter))
and run it.
$ python3 test.py usage: test.py [-h] somearg test.py: error: the following arguments are required: somearg $ python3 test.py cat You provided parameter cat!
The argparse module automatically handles help which is pretty handy
$ python3 test.py -h usage: test.py [-h] somearg positional arguments: somearg Some argument optional arguments: -h, --help show this help message and exit
Actions:
You can create a custom action if you want to validate the parameter on the fly! ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them. The action keyword argument specifies how the command-line arguments should be handled. Other than validator, here are list of supplied actions:- store - This just stores the argument’s value
- store_const - This stores the value specified by the const keyword argument
- store_true and store_false - These are special cases of 'store_const' used for storing the values True and False respectively
- append - This stores a list, and appends each argument value to the list
- append_const - This stores a list, and appends the value specified by the const keyword argument to the list
- count - This counts the number of times a keyword argument occurs
- help - This prints a complete help message for all the options in the current parser and then exits
- version - This expects a version= keyword argument in the add_argument() call, and prints version information
This blog only covers customized validators.
Define a validator class:
class ValidateParameter(argparse.Action): """Validate parameter""" def __call__(self, parser, namespace, values, option_string=None): if not values.isupper(): sys.exit("This parameter must be upper case") else: setattr(namespace, self.dest, values)
Then when you add the argument, you can insert the action which calls the "ValidateParameter" we just defined.
parser.add_argument('somearg', action=ValidateParameter, help='Some argument')
Run it again:
$ python3 test.py lowercase This parameter must be uppercase $ python3 test.py LOWERCASE You provided parameter LOWERCASE!
The source code:
import argparse import sys class ValidateParameter(argparse.Action): """Validate parameter""" def __call__(self, parser, namespace, values, option_string=None): if not values.isupper(): sys.exit("This parameter must be uppercase") else: setattr(namespace, self.dest, values) parser = argparse.ArgumentParser() parser.add_argument('somearg', action=ValidateParameter, help='Some argument') args = parser.parse_args() parameter = args.somearg print("You provided parameter {}!".format(parameter))
No comments:
Post a Comment