Overview
In Python's project development process, we sometimes need to provide the program with some interfaces that can be called through the command line. However, not directly using Command + The current file is OK, we need to set an optional variety of operation types. Therefore, it is necessary for us to parse the incoming parameters in this case. Here are a few different strategies for solving this problem, and hope that you will benefit.
Copyright notice
Copyright belongs to the author.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Coding-naga
Published: March 18, 2016
Links: http://blog.csdn.net/lemon_tree12138/article/details/50912898
Source: CSDN
More content: Category >> thinking in Python
Directory
- Overview
- Copyright notice
- Directory
- Naïve string matching scheme
- Analysis
- Advantages
- Disadvantages
- Getopt Module
- Brief introduction
- Actual Use Cases
- Optionparser Module
- Brief introduction
- Parseradd_option parameter Description
- Actual Use Cases
- Ref
Analysis of naïve string matching scheme
In fact, this method can be very directly to the surface of the program apes in the logic of this road how far. Of course, this does not contain any disrespect.
This is indeed a scheme, or even an algorithm. Because it is straightforward, so in the early stages of development, I was so bored. In addition to the complete one-to-one command, we can also encapsulate the parameters in JSON, which is more thoughtful.
About this, I don't think I need to say anything more. It's better to leave some time for the latter two solutions. However, the advantages and disadvantages of this scheme can be said.
Advantages
- Different processing for different parameters, strong pertinence
Disadvantages
- Because its pertinence is too strong, so its reusability is too poor
Getopt Module Introduction
This module is a built-in Python module. This module is designed to handle command-line parameters.
Its basic usage format is as follows:
opts, args = getopt.getopt(args, shortopts, longopts = [])
The first argument to the Getopt () method is the parameter that we passed in through the command line. But there is also a noticeable place where I need to slice the parameter list. Because the first (args[0]) command-line argument we get is the current file name, which is not what we need.
For the second parameter of Getopt (), it is shortopts; The third argument is longopts.
Shortopts such as:-H
Longopts such as: Help
Shortopts is prefixed with '-', and longopts is prefixed with '-'.
We can also use short parameters alone. The basic usage format is as follows:
opts, args = getopt.getopt(sys.argv[1"ld:")
Actual Use Cases
from__init__Import* def usage(): Print ' prama_config.py usage: ' Print '-H,--help:print help message. ' Print '-V,--version:print script version ' Print '-O,--output:input an output verb ' Print '-M,--message:send a message to someone. ' Print '--foo:test option ' Print '--fre:another test option ' def version(): Print ' prama_config.py 1.0.1 ' def output(args): Print ' Hello,%s '% args def message(sender, receiver, msg):Print"{0} Send a message to {1}, content is \ ' {2}\ '.". Format (sender, receiver, MSG) def main(argv): Try: opts, args = Getopt.getopt (argv[1:],' hvom: ', [' help= ',' message= ',' foo= ',' fre= '])exceptGetopt. Getopterror, err:PrintSTR (ERR) usage () Sys.exit (2) forO, ainchOPTsifOinch('-H ','--help '): Usage () sys.exit (1)elifOinch('-V ','--version '): Version () Sys.exit (0)elifOinch('-O ','--output '): Output (a) Sys.exit (0)elifOinch('-M ','--message '): Message (A, args[0], args[1]) Sys.exit (0)Else:Print ' unhandled option 'Sys.exit (3)if__name__ = =' __main__ ': Main (SYS.ARGV)
Optionparser Module Introduction
In front of getopt, but getopt is too small, and from the point of view of the code, the process of suspicion is very heavy. Relative getopt,optionparser is more professional grade. Optionparser option parameters are added by parser.add_option () , and then by Parser.parse_args () to resolve parameter options. The whole process is object-oriented .
Another advantage for Optionparser is that we do not need to set the Help option for Optionparser, which has been built into the module.
Parser.add_option () parameter description
- Action: Action is one of the parameters of the Parse_args () method, which indicates how optparse is handled when resolving to a command-line argument. Actions have a fixed set of values to choose from, the default is ' store ', which means that the command line parameter values are saved in the Options object. The action value is store, Store_true, Store_false three;
- dest: dest is a stored variable, and command line execution commands are saved to the value specified by Dest. For example, the-P command in the following code is saved to the PDCL variable of the options specified by dest= "PDCL";
- Default : used to set defaults for saving variables in dest above. For example, in the code below, we will make the default value false. So, the value that we access by OPTIONS.PDCLP this variable is false;
- type: used to specify the data type that holds the value of the variable in Dest. The default data type is string;
- Help : used to specify the prompt for the current command.
Actual Use Cases
fromOptparseImportOptionparserparser = Optionparser () parser.add_option ("-P","--PDBK", action="Store_true",# indicates optparse what to do when parsing to a command-line argumentdest="PDCL",# stored variablesdefault=False, help="Write PDBK data to Oracle DB") Parser.add_option ("-Z","--ZDBK", action="Store_true", dest="ZDCL",# stored variablesdefault=False, help="Write ZDBK data to Oracle DB") Parser.add_option ("-F","--file",# operation Instructionsaction="Store", dest="FileName",# stored variablesType="string",# Variable Typehelp="Write report to FILE",# Help information displayedMetavar="FILE" # Store The value of a variable) Parser.add_option ("-Q","--quiet", action="Store_false", dest="Verbose", default=True, help="Don ' t print status messages to stdout") (options, args) = Parser.parse_args ()ifOptions.pdcl is True:Print ' PDCL is true 'ifOptions.zdcl is True:Print ' ZDCL is true 'ifOptions.filename is not None: Print ("Filename={0}". Format (options.filename)) print (args)
With the explanation of the above three parameter parsing strategies, we can see that parsing using the Optionparser module is the best way to do this.
Ref
- http://blog.csdn.net/tianzhu123/article/details/7655499
- http://blog.csdn.net/lwnylslwnyls/article/details/8199454
- "Python standard library"
Python command-line option parameter resolution policy