This article is from I also have a blog reproduced over, welcome everyone click to see, help me add a bit popular ^_^ Impyy
Select module
According to the instructions from the Python reference manual, Optparse has been discarded and should be used Argparse
Tutorial Concepts
The Argparse module uses add_argument to add optional command-line parameters, such as the following:
Argumentparser.add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest]) Define how a, command-line argument should be parsed. Each parameter have its own more detailed description below, but in short they are:name or flags-either a name or a l Ist of option strings, e.g Foo Or-f,--foo. Action-the basic type of action to being taken when this argument is encountered on 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 is converted. Choices-a container of the allowable values for the argument. Required-whether or not the command-line option is 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 being added to the object returned by Parse_args ().
The above explanation actually does not need to look, directly to see the demonstration sample good:
Just want to show some information
#-*-Coding:utf-8-*-"" "Argparse Tester" "" Import 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 will output such as the following:
$ 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 shorthand for this option. --verbose is a complete spelling, all is able
Help is a helpful information. No explanation.
args = Parse_args () returns a namespace, simply by adding an optional, such as verbose. It will add the verbose to the args, and will be able to directly through the Args.verbose interview.
Suppose you want to give it an individual name, you need to add a number of dest= ' VB ' in Add_argument
This way you will be able to access it through Args.vb.
action= "Store_true" means that the option does not need to receive parameters, directly set Args.verbose = True,
Of course, suppose you don't specify-V. Then Args.verbose is False.
But assuming you remove the action= "Store_true", you must specify a value for-V. For example,-V 1
Make a summation procedure.
#-*-coding:utf-8-*-" "" Argparse Tester "" "Import 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 world "if Args.sum:results = SUM (args.numbers) print "tsum:tt%s"% results
The output is as follows:
[[email protected] 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[[email prote CTED] test]$ python t2.py 1 2 3-sinput: [1, 2, 3]result: Sum: 6
Note that this optional numbers no longer adds a "-" prefix. Since this is the location option
Assuming the nargs= "+" is removed, only one number can be entered. Because it specifies the number of values for the numbers option
Suppose to remove the type=int. Then Args.numbers is a string. Instead of actively converting to an integer
Notice that the--sum option is finally added with Default=true. This means that even if you do not specify-s on the command line, it will be set to True by default.
Only 2 optional 1 options available
#-*-Coding:utf-8-*-"" "Argparse Tester" "" Import 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 World" if 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:
[[email protected] test]$ python t2.py 1 2 3-f floatinput: [1, 2, 3]result: sum: 6.000000[[email protected] 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 the option-F is added, choices=[' int ', ' float ', is passed in. Indicates that the option can only be selected from int or float 2 of 1
Python command line parameter parsing