Python command line option Parameter Parsing Policy

Source: Internet
Author: User

Python command line option Parameter Parsing Policy
Overview

In the Python project development process, we sometimes need to provide some interfaces for the program that can be called through the command line. However, it is not directly usedCommand + current fileWe need to set a variety of optional operation types. Therefore, in this case, it is necessary to parse the input parameters. Next we will propose several different solutions to this problem, hoping to help you.

Copyright description simple string matching Solution Analysis

In fact, this method can be expressed directly.ProgrammersHow far have we gone in the logic path. Of course, this does not include any disrespect.
This is indeed a solution, or even an algorithm. Because of its straightforward nature, I was so happy at the early stage of program development. In addition to the complete one-by-one commands, we can also encapsulate the parameters in json format, which is more considerate.
I don't have to say anything about this. It is better to leave some time for the following two solutions. However, we can still talk about the advantages and disadvantages of this solution.

The advantage is that different processing is performed for different parameters, which is highly targeted. The disadvantage is that the Pertinence is too strong, so the reusability is too poor. Introduction to the getopt Module

This module is a built-in python module. This module is used to process command line parameters.
The basic format is as follows:

opts, args = getopt.getopt(args, shortopts, longopts = [])

The first parameter of the getopt () method is the parameter passed in through the command line.But here is also worth noting that I need to slice the parameter list. Because the first (args [0]) command line parameter we obtained is the name of the current file, which is not what we need.
The second parameter of getopt () isShortopts; The third parameter isLongopts.
Shortopts example:-h
Longopts example:-help
Shortopts is prefixed with '-', and longopts is prefixed.

We can also use short parameters separately. The basic format is as follows:

opts, args = getopt.getopt(sys.argv[1:], "ld:")
Practical 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' % argsdef 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='])    except getopt.GetoptError, err:        print str(err)        usage()        sys.exit(2)    for o, a in opts:        if o in ('-h', '--help'):            usage()            sys.exit(1)        elif o in ('-v', '--version'):            version()            sys.exit(0)        elif o in ('-o', '--output'):            output(a)            sys.exit(0)        elif o in ('-m', '--message'):            message(a, args[0], args[1])            sys.exit(0)        else:            print 'unhandled option'            sys.exit(3)if __name__ == '__main__':    main(sys.argv)
Introduction to the OptionParser Module

As mentioned above, getopt is too small, and from the code point of view,Process-orientedThe suspect is very heavy. Relative to getopt,OptionParserIt looks quite professional. OptionParser passedParser. add_option ()Add option parameters, and then passParser. parse_args ()Resolution Parameter options. The entire process is veryObject-oriented.
Another advantage of OptionParser is that you do not need to set the help option for OptionParser. The help option has been embedded into the module.

Parser. add_option () parameter description Action:Action is one of the parameters of the parse_args () method. It instructs optparse what to do when parsing a command line parameter. Actions has a set of fixed values to choose from. The default value is 'store', indicating that the value of the command line parameter is saved in the options object. Action values include store, store_true, and store_false; Dest:Dest is the stored variable. The command line execution command will be saved to the value specified by dest. For example, the-p command in the following code will be saved to the pdcl variable of options specified by dest = "pdcl; Default:It is used to set the default value for saving variables in the preceding dest. For example, in the following code, the default value is set to False. The value accessed through the options. pdclp variable is False; Type:Specifies the data type used to save variable values in the dest. The default data type is string; Help:Specifies the prompt information of the current command. Practical Use Cases
From optparse import OptionParserparser = OptionParser () parser. add_option ("-p", "-- pdbk", action = "store_true", # instructs optparse how to handle dest = "pdcl" when parsing a command line parameter ", # stored variables default = False, help = "write pdbk data to oracle db") parser. add_option ("-z", "-- zdbk", action = "store_true", dest = "zdcl", # The stored variable default = False, help = "write zdbk data to oracle db") parser. add_option ("-f", "-- file", # Operation Command action = "store", dest = "filename", # Storage variable type = "string ", # variable type help = "write report to FILE", # The displayed help information metavar = "FILE" # the value of the stored 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 () if options. pdcl is True: print 'pdcl is true' if options. zdcl is True: print 'zdcl is true' if options. filename is not None: print ("filename = {0 }". format (options. filename) print (args)

Through the description of the above three parameter resolution policies, we can see that using the OptionParser module for parsing is the best way.

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.