Python optparse module Use instance _python

Source: Internet
Author: User

When you use a command line, if you want to add an option, Python 2.3 Adds a new module called Optparse, which is also dedicated to handling command-line options.

Copy Code code as follows:

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, action is Store,store_true,store_false, dest is stored variables, default is defaults, Help is helpful tips

Finally, the Parse_args () function is parsed to obtain the option, such as the OPTIONS.PDCL value.
Basic usage Process:

"1. Produce a optparse. A Optionparser object. You can give the "command list of the program" (usage) as a reference, and give it to Optionparser's construction:

Copy Code code as follows:

From Optparse import Optionparser
Msg_usage = "myprog[-F <filename>][-S <xyz>] arg1[, arg2 ...]"
Optparser = Optionparser (msg_usage)

"2.Call Optionparser.add_option () to join accepted option:
Copy Code code as follows:

Optparser.add_option ("F"),
"--file",
Action = "Store",
Type = "string",
Dest = "FileName")

There are many types of reference action, which are "store", so even if the omission is not a nuisance, other action species will continue to be stated below.

If you have more than one option, repeat the above method Add (note: The action parameters are omitted):

Copy Code code as follows:

Optparser.add_option ("-S",
"--someopt",
Type = "string",
Dest = "Someopt")

"3.Call Optionparser.parse_args () to read. Without a reference, optionparser the sys.argv[1: "to read the image." Optionparser.parse_args () will pass back a tuple, by Optparse. Values are composed of a list. The following example is involved in a bogus list of parameters:
Copy Code code as follows:

Fakeargs = [' f ', ' thefile.txt ', '-s ', ' xyz ', ' arg1 ', ' arg2 ', ' arge ']

Options, args = Optparser.parse_args (Fakeargs)

Print Options.filename
Print options.someopt
Print args

The final output results:
Copy Code code as follows:

Thefile.txt
Xyz
[' Arg1 ', ' arg2 ', ' arge ']

This is a simple example of how optionparser is used in general. Through this example, you can see if you add option to the program and you get option argument and positional argument in the program. Optionparser.parse_args () There are many uses, the following will explain a part.

To add flag option to the program:

Many Unix commands have "-V", "-q" option, representing "provide detailed information" or "do not display information." To do this, simply add the following option to the program:

Copy Code code as follows:

Parser.add_option ("-V", action= "Store_true", dest= "verbose")
Parser.add_option ("Q", action= "Store_false", dest= "verbose")
opts, args = Parser.parse_args ()

The first add_option () adds a "-V" option, and if "-V" appears in the command column parameters, the opts.verbose will be True; Conversely, the second add_option () adds a "-q" option; if the command column The "Q" appears in the parameters, and the opts.verbose will be False, and the two are not inconsistent, the program can be designed to: when "V" is received, the details are displayed, and when "Q" is received, the message is either sketchy or completely visible, and when neither is received, a general message is displayed.

Set option's preset value:

All of the above examples assume that the command example receives the expected option, so what is the option value received if there is no option? The answer is none!. If you want to provide a preset for option, just Optionparser.parse_args () You can specify the parameters default:

Copy Code code as follows:

Parser.add_option ("-V", action= "Store_true", dest= "verbose", default = True)
Parser.add_option ("Q", action= "Store_false", dest= "verbose")
opts, args = Parser.parse_args ()

The above code adds two options to the program, when "-V" does not appear, the Opts.verbose preset is True, and when "-Q" is specified, the opts.verbose is set to False, a bit different from the previous example. Let's look at the next example:
Copy Code code as follows:

Parser.add_option ("-V", action= "Store_true", dest= "verbose", Default=false)
Parser.add_option ("Q", action= "Store_false", dest= "verbose", default=true)

What is the Opts.verbose's preset? The answer is True, and the last option preset assigned to the same goal is used.

General option can also be added to the preset value:

Copy Code code as follows:

Parser.add_option ("F", action= "store", dest= "FileName", default = "DefaultConfig.txt")

For the program to add the saying:

Standard Unix commands are mostly "-H", "--help" option, which will be used to explain the printed out. Specifying the "Help" parameters in Optionparser.parse_args () and specifying the specified string can be added to this option by stating:

Copy Code code as follows:

Parser.add_option ("-V",
Action= "Store_true",
dest= "Verbose",
Default=false,
Help= "Make lots of noise [default]")

When the program receives "-H" or "--help", when handing it to Optionparser, it automatically prints out the contents of the description and ignores the other argument:
Copy Code code as follows:

Usage: <yourscript> [options] arg1 arg2

Options
-H,--help show this Help 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 '

Remember to start by referring to the msg_usage of the optionparser constructs? The Optparse Kit also provides some support for usage messages. Using the "%prog" keyword in usage, Optionparser automatically replaces it with a program name, that is, Sys.args[0]:
Copy Code code as follows:

Usage = "Usage:%prog [options] arg1 arg2"

If the program is called "Myprog", the usage that appears in Help messages is:
Copy Code code as follows:

Usage = "Usage:myprog [options] arg1 arg2"

If the Optionparser does not receive any parameters, it automatically generates a usage message:
Copy Code code as follows:

"Usage:%prog [options]"

The premise is that the program does not have positional argument. Don't worry. option in the way the help message is arranged, Optionparser will take care of everything, as shown in the previous program.

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.