Python optparse module instance, pythonoptparse

Source: Internet
Author: User

Python optparse module instance, pythonoptparse

If you want to add options when using command lines, a new module named optparse is added in python 2.3, which is also used to process command line options.
Copy codeThe Code is 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. 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.
Basic Procedure:

"1.Generates an optparse. OptionParser object. At the time of production, you can define the "program command List" (usage) as a numeric value and send it to the OptionParser's constructor:

Copy codeThe Code is 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 the accepted option:
Copy codeThe Code is as follows:
OptParser. add_option ("-f ",
"-- File ",
Action = "store ",
Type = "string ",
Dest = "fileName ")

There are many types of batch data actions. They are set to "store", so even if they are omitted, other types of actions will be explained below.

If there is more than one option, repeat the preceding method (Note: The number of action parameters is omitted below ):
Copy codeThe Code is as follows:
OptParser. add_option ("-s ",
"-- Someopt ",
Type = "string ",
Dest = "someopt ")

"3.Call OptionParser. parse_args () to perform decoding. If no input parameter is available, OptionParser will parse the object as sys. argv [1. OptionParser. parse_args () returns a tuple, which is formed by optparse. Values and a list. In the following example, create a dummy data column:
Copy codeThe Code is as follows:
FakeArgs = ['-F', 'thefile.txt', '-S', 'xyz', 'arg1', 'arg2', 'arg']

Options, args = optParser. parse_args (fakeArgs)

Print options. fileName
Print options. someopt
Print args

The final result is as follows:
Copy codeThe Code is as follows:
Thefile.txt
Xyz
['Arg1', 'arg2', 'arg']

This is a simple example, indicating the General Usage of OptionParser. Through this example, we can see that if you add option to the program and get option argument and positional argument in the program. OptionParser. parse_args () may be used in many ways. The following describes some of them.

Add the flag option to the program:

Many Unix commands have the option "-v" and "-q", which indicates "providing the warning message" or "not showing the warning message ". To do this, you only need to add the following options to the program:
Copy codeThe Code is 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 () is added with a "-v" option. If "-v" is displayed in the number of arguments in the Command column, opts. verbose will be True; on the contrary, the second add_option () is added with a "-q" option; if "-q" is displayed in the Command column ", opts. verbose will be False, and these two will not be in conflict. The program can be designed to show negative response when "-v" is received; when "-q" is received, the alarm indicates a rough alarm or no alarm. If neither of them receives the alarm, the alarm is normal.

Set the default value of option:

In the preceding example, if the command is set to false, the option in the timeout period will be received. So if there is no option, what is the option value received? The answer is None! If you want to provide the default value for option, you only need to specify the default value in OptionParser. parse_args:
Copy codeThe Code is 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 program adds two options to the program. When "-v" does not appear, opts. verbose duration is set to True. When "-q" is specified, opts. verbose is set to False, which is a little different from the previous example. Let's look at the next example:
Copy codeThe Code is 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 reset value of opts. verbose? The answer is True. The last option setting value specified to the same object will be used.

You can also add the following option values:
Copy codeThe Code is as follows:
Parser. add_option ("-f", action = "store", dest = "fileName", default = "defaultConfig.txt ")

Add instructions for the program:

Most of the Unix Commands marked as "-h", "-- help" options will be printed with instructions. Specify the "help" numeric value in OptionParser. parse_args () and specify the declarative string. You can add a description for this option:
Copy codeThe Code is 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" and returns it to OptionParser for release, it automatically prints the explicit content, ignoring other argument:
Copy codeThe Code 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)
-FFILE, -- file = FILE write output to FILE
-MMODE, -- mode = MODE interaction mode: one of 'novice ', 'intermediate'
[Default], 'expert'

Do you still remember to mention the MSG_USAGE number for the OptionParser constructor? The optparse kit also provides some support for usage messages. When you use the "% prog" keyword in usage, OptionParser automatically replaces it with the program name, that is, sys. args [0]:
Copy codeThe Code is as follows:
Usage = "usage: % prog [options] arg1 arg2"

If the program name is "myprog", the usage in the help messages will be:
Copy codeThe Code is as follows:
Usage = "usage: myprog [options] arg1 arg2"

If the OptionParser constructor does not receive any metric data, it will automatically generate a usage warning:
Copy codeThe Code is as follows:
"Usage: % prog [options]"

The premise is that the program does not have positional argument. When option is arranged in the help messages, OptionParser will handle everything, as shown in the previous program.

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.