Python Module Learning--optparse__python

Source: Internet
Author: User

Http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html


Python has two built-in modules for handling command-line arguments:

One is getopt, "Deep in Python" also mentions that only simple processing of command-line parameters;

The other is Optparse, which is powerful and easy to use, and makes it easy to generate standard, UNIX/POSIX-compliant command-line instructions. Sample

The following is a simple example of using optparse: from optparse import optionparser   [...]    parser = optionparser ()    parser.add_option ("F",  "--file",  dest= " FileName ",                      help= "Write report to file",  metavar= "FILE")    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 ()     

Now, you can enter at the command line: <yourscript>--file=outfile-q <yourscript>-f outfile--quiet <yourscript>--quiet --file outfile <yourscript>-q-foutfile <yourscript>-qfoutfile

The above commands are the same effect. In addition, Optparse also automatically generates command line help for us: <yourscript>-H <yourscript>--help

Output: Usage: <yourscript> [options] Options:-H,--help show this help and Exit-f FIL E,--file=file write to File-q,--quiet don ' t print status messages to stdout

Simple Process

First, you must import the Optionparser class and create a Optionparser object: from optparse import Optionparser [...] Parser = Optionparser ()

Then, use Add_option to define the command-line arguments: Parser.add_option (opt_str, ..., Attr=value, ...)

Each command-line argument consists of a parameter name string and an argument property. such as- f or –file , respectively, are the length parameter names: Parser.add_option ("F", "--file", ...)

Finally, once you have defined all command-line arguments, call Parse_args () to resolve the program's command line: (options, args) = Parser.parse_args ()

Note: You can also pass a command line argument list to Parse_args (); otherwise, the default is to use Sys.argv[:1].

Parse_args () returns two values: Options, which is an object (Optpars. Values), with the command line argument value saved. As long as you know the command line argument name, such as file, you can access its corresponding value: Options.file. Args, which is a list of positional arguments. Actions

The action is one of the parameters of the Parse_args () method, which indicates how the Optparse is handled when parsing to a command-line argument. The actions have a fixed set of values to choose from, and the default is 'store ', which means that the command line parameter values are saved in the Options object.

Example Parser.add_option ("F", "--file", action= "store", type= "string", dest= "filename") args = ["F", " Foo.txt "] (options, args) = Parser.parse_args (args) print Options.filename

Finally, the "Foo.txt" will be printed out.

When optparse resolves to '-f ', it continues parsing the ' foo.txt ' and then saves ' foo.txt ' to options.filename. When Parser.args () is invoked, the Options.filename value is ' foo.txt '.

You can also specify that the type parameter in the Add_option () method is a different value, such as int or float, and so on: Parser.add_option ("-N", type= "int", dest= "num")

By default, type is ' string '. Also, as indicated above, long parameter names are optional. In fact, the dest parameter is optional. If the Dest parameter is not specified, the value of the options object is accessed using the parameter name of the command line.

The store also has two other forms: store_true and Store_false , which are used to handle situations with no values following the command line arguments. command line arguments such as-v,-q: Parser.add_option ("-V", action= "Store_true", dest= "verbose") parser.add_option ("-Q", action= "Store_" False ", dest=" verbose ")

In this case, when parsing to '-V ', Options.verbose will be given a True value, whereas parsing to ' Q ' will be given a value of False.

Other actions are as follows:

store_const ,append ,count ,callback .

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.