Python Command Line Parameter Parsing
ImPyy
Select Module
According to the instructions in the python reference manual, optparse has been deprecated and argparse should be used.
Tutorial concepts
The argparse module uses add_argument to add optional command line parameters. The prototype is as follows:
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are: name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections. default - The value produced if the argument is absent from the command line. type - The type to which the command-line argument should be converted. choices - A container of the allowable values for the argument. required - Whether or not the command-line option may be omitted (optionals only). help - A brief description of what the argument does. metavar - A name for the argument in usage messages. dest - The name of the attribute to be added to the object returned by parse_args().
You don't need to check the above description. You can check the example directly:
Just want to display some information
# -*- coding: utf-8 -*-argparse testerimport argparseparser = argparse.ArgumentParser(description='argparse tester')parser.add_argument(-v, --verbose, help=increase output verbosity, action=store_true)args = parser.parse_args()if args.verbose: print hello world
It outputs the following output:
$ python t.py$ python t.py -vhello world$ python t.py -husage: t.py [-h] [-v]argparse testeroptional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity
Here,-v is short for this option. -- verbose is a complete spelling and can all be used.
Help is the help information, not explained
Args = parse_args () returns a namespace. If you add an option, such as verbose, it adds verbose to args and can be accessed directly through args. verbose.
If you want to give it an alias, you need to add a parameter dest = 'vb 'in add_argument'
In this way, you can access it through args. vb.
Action = store_true indicates that this option does not need to receive parameters. Set args. verbose = True directly,
Of course, if you do not specify-v, then args. verbose is False.
However, if you remove action = store_true, you must specify a value for-v, such as-v 1.
Make a summation Program
# -*- coding: utf-8 -*-argparse testerimport argparseparser = argparse.ArgumentParser(description='argparse tester')parser.add_argument(-v, --verbose, help=increase output verbosity, action=store_true)parser.add_argument('numbers', type=int, help=numbers to calculate, nargs='+')parser.add_argument('-s', '--sum', help=sum all numbers, action='store_true', default=True)args = parser.parse_args()print Input:, args.numbersprint Result:results = args.numbersif args.verbose: print hello worldif args.sum: results = sum(args.numbers) print tSum:tt%s % results
The output is as follows:
[pan@pan-pc test]$ python t2.py -husage: t2.py [-h] [-v] [-s] numbers [numbers ...]argparse testerpositional arguments: numbers numbers to calculateoptional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity -s, --sum sum all numbers[pan@pan-pc test]$ python t2.py 1 2 3 -sInput: [1, 2, 3]Result: Sum: 6
Note that this option numbers is no longer prefixed with "-" because it is a location option.
If you remove nargs = +, you can only enter one number. Because it specifies the number of values of the number Option
If type = int is removed, args. numbers is a string instead of an integer.
Note that the -- sum option is added with default = True, which means that it will be set to True by default even if you do not specify-s in the command line.
Only two options can be selected.
# -*- coding: utf-8 -*-argparse testerimport argparseparser = argparse.ArgumentParser(description='argparse tester')#group = parser.add_mutually_exclusive_group()parser.add_argument(-v, --verbose, help=increase output verbosity, action=store_true)parser.add_argument('numbers', type=int, help=numbers to calculate, nargs='+')parser.add_argument('-s', '--sum', help=sum all numbers, action='store_true', default=True)parser.add_argument('-f', '--format', choices=['int', 'float'], help='choose result format', default='int')args = parser.parse_args()print Input:, args.numbersprint Result:results = args.numbersif args.verbose: print hello worldif args.format == 'int': format = '%d'else: format = '%f'if args.sum: results = sum(args.numbers) print 'tsum:tt%s' % (format % results)
The output is as follows:
[pan@pan-pc test]$ python t2.py 1 2 3 -f floatInput: [1, 2, 3]Result: sum: 6.000000[pan@pan-pc test]$ python t2.py 1 2 3 -f doubleusage: t2.py [-h] [-v] [-s] [-f {int,float}] numbers [numbers ...]t2.py: error: argument -f/--format: invalid choice: 'double' (choose from 'int', 'float')
When option-f is added, the choices = ['int', 'float'] parameter is input, indicating that this option can only be selected from 2 of int or float.