Python command-line option parameter resolution policy

Source: Internet
Author: User

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. Just, 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. I hope you're on purpose.

Copyright notice

Copyright belongs to all authors.
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
Lots of other content: Category >> thinking in Python

Folder

    • Overview
    • Copyright notice
    • Folder
    • Naïve string matching scheme
      • Analysis
      • Strengths
      • Disadvantages
    • Getopt Module
      • Simple Introduction
      • Actual Use Cases
    • Optionparser Module
      • Simple Introduction
        • Parseradd_option parameter Description
      • Actual Use Cases
    • Ref

Analysis of naïve string matching scheme

In fact, this approach can be very direct to the programmer on the logic of the way to go far.

Of course, this does not include any disrespect whatsoever.
This is indeed a scheme, even one that can be said to be an algorithm. Because of its directness. So at the beginning of the program development, I was so bored.

Except for the one-and-one command. We are also able to encapsulate the parameters in JSON, which makes them more considerate.
About. I don't think I need to say anything more about that.

It is better to leave some time for the latter two solutions. It is still possible to talk about the advantages and disadvantages of this program.

Strengths
    1. Different processing for different parameters, strong pertinence
Disadvantages
    1. Its reusability is too poor because of its pertinence
Getopt Module Simple Introduction

This module is a built-in Python module. This module is specifically 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 number of parameters that we pass through the command line.

But there is also a noticeable place where I need to slice the list. Because the first (args[0]) command line we get is the current file name. This is not what we need.
For the second parameter of Getopt (), it is shortopts. The third parameter is longopts.
Shortopts analogy:-H
Longopts analogy: Help
Shortopts is prefixed with '-', and longopts is prefixed with '-'.

We are also able to use short parameters alone. Basic usage formats such as the following:

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 Simple Introduction

Before speaking of Getopt, just getopt is too small, and from the point of view of the code. The process-oriented suspicion is very heavy.

Relative getopt,optionparser is more professional grade.

Optionparser the option number by parser.add_option () . The Parser.parse_args () is then parsed with the parameter options.

The whole process is very object-oriented .
Another advantage for Optionparser is that we do not need to set the Help option for Optionparser. The Help option has been built into the module.

Parser.add_option () parameter description
    1. Action: Action is one of the parameters of the Parse_args () method, which indicates how the optparse should be handled when parsing to a command-line parameter. Actions have a fixed set of values to choose from, the default is ' store ', which means that the command-line values are saved in the Options object.

      The action value is store, Store_true, Store_false three;

    2. dest: dest is a stored variable, command line Run command will be saved to dest specified value.

      For example, the-P command in the following code. will be saved to the PDCL variable of the options specified by dest= "PDCL";

    3. Default : used to set defaults for saving variables in dest above. For example, in the following code, we will make the default value false.

      So, the value that we visit by OPTIONS.PDCLP this variable is false;

    4. type: used to specify the data type that holds the value of the variable in Dest.

      The default data type is string;

    5. 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 parameterdest="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)

By explaining the above three parameters, you 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.