How to use the Python optionParser module (help Command)

Source: Internet
Author: User
Tags exception handling in python


Python has two built-in modules used to process command line parameters: getopt, which is also mentioned in Deep in python. It can only process command line parameters. optparse, it 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 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


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 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.
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:
Python code

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.
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. In this case, you can use OptonGroup:


Group = OptionGroup (parser, ''dangerous option '',
''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
Fool 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.
Complete Program example

 

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

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.