Python optparse module Learning

Source: Internet
Author: User

Reference: http://docs.python.org/2/library/optparse.html

Python has two built-in modules for processing command line parameters:

One is getopt, and getopt can only process command line parameters.

The other is optparse, which is a Python module that allows program designers to easily design simple, easy to use, and compliant with standard Unix Command columns. Generate usage and help information.

The following is a simple example script optparse_exampl_1.py:

[Root @ localhost python] # vim optparse_exampl_1.py

#!/usr/bin/env pythonfrom optparse import OptionParserparser = 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 the following in the command line:

<yourscript> --file=outfile -q<yourscript> -f outfile --quiet<yourscript> --quiet --file outfile<yourscript> -q -foutfile<yourscript> -qfoutfile

The above commands have the same effect. In addition, optparse also automatically generates command line help information for us:

<yourscript> -h<yourscript> --help

Optparse prints the options and help information of the script:

[root@localhost python]# ./optparse_exampl_1.py -hUsage: optparse_exampl_1.py [options]                                                                                                                                             Options:  -h, --help            show this help message and exit  -f FILE, --file=FILE  write report to FILE  -q, --quiet           don't print status messages to stdout

The following describes how to use optparse: aptparse is flexible and powerful in most cases. This article describes common optparse usage. First, import the OptionParser class and create a class in the main program:
from optparse import OptionParser[...]parser = OptionParser()

Now you can define command line options. The basic syntax is:

parser.add_option(opt_str, ...,                  attr=value, ...)

Each option has one or more options, such as-f or -- file. Generally, each option has a short option and a long option. For example:

parser.add_option("-f", "--file", ...)

You can define as many short options and as many long options as possible (including zero), but at least there must be an option string as a whole. Finally, once you have defined all the command line parameters, call parse_args () to parse the program's command line:
(options, args) = parser.parse_args()
Note: You can also pass a command line parameter list to parse_args (); otherwise, sys. argv [: 1] is used by default. Parse_args () returns two Values: options, which is an object optpars. Values) and stores the value of the command line parameter. As long as you know the name of the command line parameter, such as file, you can access its corresponding value: options. file. Args is a list composed of positional arguments. Option operations: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. 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, we will print the example foo.txt ". When optparse is merged to '-f', 'foo.txt' following the extension will be saved to options. filename. After parser. args () is called, the options. filename value is 'foo.txt '. You can also specify the type parameter in the add_option () method as another value, such as int or float:
parser.add_option("-n", type="int", dest="num")

Note: This option does not have a long option, and the long option is also optional. If the dest option is not specified, the options object value is accessed using the command line parameter name. Store also has two other forms: stort_true and store_false, which are used to process command line parameters such as-v and-q without a value after the command line option.

parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose")

In this case, when it is parsed to '-V', options. verbose, it will be assigned a value of True. Otherwise, if it is parsed to'-Q', it will be assigned a value of False.

Other actions values include:

Store_const, append, count, and callback

Default Value

The parse_args () method provides a default parameter for setting the default value. For example:

parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose", default=True)

Or use set_defaults for example:

parser.set_defaults(verbose=True)parser.add_option(...)(options, args) = parser.parse_args()

Program Generation helpAnother convenient function of optparse is to automatically generate program help information. You only need to specify the help text for the help option of the add_option () method:
usage = "usage: %prog [options] arg1 arg2"parser = OptionParser(usage=usage)parser.add_option("-v", "--verbose",                  action="store_true", dest="verbose", default=True,                  help="make lots of noise [default]")parser.add_option("-q", "--quiet",                  action="store_false", dest="verbose",                  help="be vewwy quiet (I'm hunting wabbits)")parser.add_option("-f", "--filename",                  metavar="FILE", help="write output to FILE")parser.add_option("-m", "--mode",                  default="intermediate",                  help="interaction mode: novice, intermediate, "                       "or expert [default: %default]")

When optparse parses the-h or-help command line parameters, it will call parser. print_help () to print the program's help information:

Usage: <yourscript> [options] arg1 arg2                                                      Options:  -h, --help            show this help message and exit  -v, --verbose         make lots of noise [default]  -q, --quiet           be vewwy quiet (I'm hunting wabbits)  -f FILE, --filename=FILE                        write output to FILE  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or                        expert [default: intermediate]

Note: After the script prints the help information, it exits and does not parse other option parameters.) use the custom program:
usage = "usage: %prog [options] arg1 arg2"
This line of information is first printed before the program's options. When % prog, optparse will be replaced by the string of the current program name, such as OS. path. basename. (sys. argv [0]). If you do not provide custom usage information, optparse uses "usage: % prog [options]" by default. When you define the help information of command line parameters, you don't have to worry about the problem caused by line breaks. optparse will handle all this. Setting the metavar parameter in the add_option method helps remind users of the expected parameters of this command line parameter, such as metavar = "mode ":
-m MODE, --mode=MODE
Note: The strings in the metavar parameter are automatically capitalized. In the help information of the help parameter, % default can be used to insert the default value of this command line parameter. If the program has many command line parameters, you may want to group them. OptionGroup:
group = OptionGroup(parser, "Dangerous Options",                    "Caution: use these options at your own risk.  "                    "It is believed that some of them bite.")group.add_option("-g", action="store_true", help="Group option.")parser.add_option_group(group)

The output is as follows:

Usage: <yourscript> [options] arg1 arg2                         Options:  -h, --help            show this help message and exit  -v, --verbose         make lots of noise [default]  -q, --quiet           be vewwy quiet (I'm hunting wabbits)  -f FILE, --filename=FILE                        write output to FILE  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or                        expert [default: intermediate]                           Dangerous Options:    Caution: use these options at your own risk.  It is believed that some    of them bite.                             -g                  Group option.

Complete columns:

group = OptionGroup(parser, "Dangerous Options",                    "Caution: use these options at your own risk.  "                    "It is believed that some of them bite.")group.add_option("-g", action="store_true", help="Group option.")parser.add_option_group(group)                    group = OptionGroup(parser, "Debug Options")group.add_option("-d", "--debug", action="store_true",                 help="Print debug information")group.add_option("-s", "--sql", action="store_true",                 help="Print all SQL statements executed")group.add_option("-e", action="store_true", help="Print every action done")parser.add_option_group(group)

This article from the "ordinary days" blog, please be sure to keep this source http://wolfchen.blog.51cto.com/2211749/1230061

Related Article

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.