python argparse only allow certain values 1

python argparse only allow certain values

...
parser.add_argument('--val',
                    choices=['a', 'b', 'c'],
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])

Here is what the above code is Doing:
1. Create a parser object
2. Add an argument to the parser object
3. Parse the arguments

The parser object is an instance of the ArgumentParser class.

The add_argument() method is used to add an argument to the parser object.

The parse_args() method is used to parse the arguments.

The parse_args() method returns an object containing the arguments passed to the script.

The object returned by parse_args() has the same methods and attributes as the Namespace class.

The object returned by parse_args() has the following methods and attributes:

args.name
args.age
args.val

Similar Posts