Python optionParser module usage example tutorial, pythonoptionparser

Source: Internet
Author: User

Python optionParser module usage example tutorial, pythonoptionparser

This article describes how to use the optionParser module in Python in detail in the form of examples. It is of great reference value for deep learning Python. Share it with you for your reference. The specific analysis is as follows:

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

One is getopt, which is also mentioned in Deep in python. It can only process command line parameters;

The other is optparse, Which is powerful and easy to use and can easily generate standard command line instructions that comply with Unix/Posix specifications.

Example:

from optparse import OptionParser parser = OptionParser() parser.add_option("-p", "--pdbk", action="store_true",    dest="pdcl",    default=False,    help="write pdbk data to oracle db") parser.add_option("-z", "--zdbk", action="store_true",    dest="zdcl",    default=False,    help="write zdbk data to oracle db") (options, args) = parser.parse_args() if options.pdcl==True:  print 'pdcl is true' if options.zdcl==True:  print 'zdcl is true' 

Add_option is used to add options. Actions include store, store_true, and store_false. dest is the storage variable, default is the default value, and help is the help prompt.

Finally, the parse_args () function is parsed to obtain the options, such as the options. pdcl value.
 
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:

<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 

Output:

usage: <yourscript> [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 

Simple process

First, you must import the OptionParser class to create an OptionParser object:

from optparse import OptionParser  [...]  parser = OptionParser()

Then, use add_option to define the command line parameters:

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

Each command line parameter is composed of a parameter name string and parameter attributes. For example, the-f or-file parameter names are respectively long and short:

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

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) that stores the command line parameter Values. As long as you know the name of the command line parameter, such as file, you can access its corresponding value: options. file.
② Args, which is a list composed of positional arguments.

Actions

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.

The sample code is as follows:

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")

By default, type is 'string '. As shown above, long parameter names are also optional. In fact, the dest parameter is also optional. If the dest parameter is not specified, the parameter name of the command line is used to access the value of the options object.
Store can also be in the following two forms: store_true and store_false, which are used to handle situations where a value is not followed by a command line parameter. Command line parameters such as-v and-q:

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("-f","--file", action="store", dest="filename", default="foo.txt") parser.add_option("-v", action="store_true", dest="verbose", default=True) 

Or use set_defaults ():

parser.set_defaults(filename="foo.txt",verbose=True) parser.add_option(...) (options, args) = parser.parse_args()

Generate program help

Another convenient function of optparse is to automatically generate program help information. You only need to specify the help text for the help parameter 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 help information is printed, optparse exits and does not parse other command line parameters.
The preceding example explains how to generate help information step by step:

① User-Defined program usage information (usage message ):
 
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.
④ Use % default in help information of the help parameter to insert the default value of this command line parameter.

If the program has many command line parameters, you may want to group them. In this case, you can use OptonGroup:

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 following is the help information that will be printed:

usage: [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)  -fFILE, --file=FILE write output to FILE  -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'    [default], 'expert'   Dangerous Options:  Caution: use of these options is at your own risk. It is believed that  some of them bite.  -g   Group option. 

Show program version

Like usage message, you can specify the version parameter when creating the OptionParser object to display the version information of the current program:

parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") 

 
In this way, optparse automatically interprets the-version command line parameters:

$ /usr/bin/foo --version foo 1.0 

Exception Handling

Including program and user exceptions. Here we mainly discuss user exceptions, which are exceptions caused by invalid and incomplete command line parameters entered by users. Optparse can automatically detect and handle user exceptions:

$ /usr/bin/foo -n 4x usage: foo [options]  foo: error: option -n: invalid integer value: '4x'  $ /usr/bin/foo -n usage: foo [options]  foo: error: -n option requires an argument 

You can also use parser. error () to customize the handling of some exceptions:

(options, args) = parser.parse_args() [...] if options.a and options.b:  parser.error("options -a and -b are mutually exclusive") 

In the preceding example, when the-B and-B command line parameters exist simultaneously, "options-a and-B are mutually exclusive" is printed to warn the user.
If the preceding exception handling method does not meet the requirements, you may need to inherit the OptionParser class and reload the exit () and erro () methods.

An example of a complete program is as follows:

from optparse import OptionParser [...] def main():  usage = "usage: %prog [options] arg"  parser = OptionParser(usage)  parser.add_option("-f", "--file", dest="filename",    help="read data from FILENAME")  parser.add_option("-v", "--verbose",    action="store_true", dest="verbose")  parser.add_option("-q", "--quiet",    action="store_false", dest="verbose")  [...]  (options, args) = parser.parse_args()  if len(args) != 1:  parser.error("incorrect number of arguments")  if options.verbose:  print "reading %s..." % options.filename  [...]  if __name__ == "__main__":  main() 

I believe this article provides some reference for everyone's Python program design.


What is the concept of a module in python? Can I use a simple example?

A module is a file, and the imported file is imported into the corresponding module. You can use the classes, functions, variables, and other information defined in the module. If there are many modules, you can use packages to manage them. You can put the files into a folder and add a _ init _. py file.

Use the import call module in python

For example:
Import modulename
If you modify it, you need:
Reload (modulename)

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.