Argpaser is a very useful command-line parsing module in Python, which makes it easy to create user-friendly command-line programs. and Argparse automatically generates help messages and error messages.
One, example
For example, take a few integers from the command line, and then get their and or their maximum values.
ImportArgparseparser= Argparse. Argumentparser (description='Process some integers.') parser.add_argument ('integers', metavar='N', Type=int, nargs='+', Help='An integer for the accumulator') parser.add_argument ('--sum', dest='Accumulate', action='Store_const', the const=sum, default=Max, help='sum the integers (default:find the max)') args=Parser.parse_args ()PrintArgs.accumulate (Args.integers)
Entering prog.py-h from the command line displays the following information
$ prog.py-husage:prog.py [-h] [--sum] N [n ...] Process some integers.positional arguments:n for-H,--help and -- Sum sum the integers (default:find the max)
If you use the appropriate parameters, you can also sum or get the maximum value.
$ prog.py 1 2 31 2 3 4--sum10
If an incorrect argument is passed, an error message is returned.
$ prog.py a b cusage:prog.py [-h] [--'a'
Here we explain this example in detail:
1. Create parserFirst, create a Argumentparser object.
>>> parser = Argparse. Argumentparser (description='Process some integers. ')
The Argumentparser object holds the necessary information to parse the command-line arguments.
2. Adding ParametersThe parameters in the command line are saved to the Argumentparser object by calling the Add_argument () method.
>>> Parser.add_argument ('integers', metavar='N', Type=int, nargs='+',... Help='An integer for the accumulator')>>> Parser.add_argument ('--sum', dest='Accumulate', action='Store_const',... Const=sum, default=Max,... Help='sum the integers (default:find the max)')
Calling Parse_args () later will return an object that contains the two properties of integers and accumulate, integers is a list, and accumulate can be the sum () function (if--sum is specified) or the max () function.
3. Parsing parameters
Returns a Namespace object by parsing the parameter with the Parse_args () method.
>>> Parser.parse_args (['--sum'7'- 1"]) Namespace (accumulate=<built-in function Sum>, integers=[7,-1, 42])
If this function is called in a script, Parse_args () will not parse any parameters. Argumentparser automatically detects command-line arguments from the SYS.ARGV.
Python command-line parsing tool argparse module "1"