Python optparse Module usage examples

Source: Internet
Author: User
With the command line, if you want to add an option, a new module called Optparse is added to Python 2.3, which is also dedicated to handling commands.
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, action is Store,store_true,store_false, etc., dest is a stored variable, default is the default, help is a helpful hint

Finally, by parsing the Parse_args () function, you get the option, such as the value of OPTIONS.PDCL.
Basic usage Flow:

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

Copy the Code code as follows:


From Optparse import Optionparser
Msg_usage = "myprog[-F [-S ] 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 kinds of action, and the preset is "store", so even if omitted, other action species will continue to be stated below.

If there is more than one option, repeat the above method (note: The action parameters are omitted below):
Copy the Code code as follows:


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


"3.Call Optionparser.parse_args () to read. If there are no incoming parameters, the Optionparser preset will be sys.argv[1:] for the image to be read. Optionparser.parse_args () will pass back a tuple, by Optparse. Values and a list are composed. The following example follows a bogus list of parameters:
Copy CodeThe code is 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 results of the final output are:
Copy CodeThe code is 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 that if you add option to the program, and you get option argument and positional argument in the program. Optionparser.parse_args () There is a lot of usage, and here's a part of it.

To add flag option to the program:

Many Unix commands have "-V", "-q" option, which means "provide details" or "Do not show messages". To do this, simply add the following option to the program:
Copy the 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; if "-V" is present in the command list, Opts.verbose will be True; instead, the second add_option () adds a "-q" option; if the command column "-Q" In the parameters, the Opts.verbose will be False, the two are not inconsistent, the program can be designed to: when the "-V" is received, the details of the message, when the "-Q" is received, the summary information, or completely does not show, when both are not received, the general message is displayed.

Set the default value for option:

The example above assumes that the command example receives the option in the preset, so what is the option value if the option is not available? The answer is none!. If you want to provide a preset value for option, just Optionparser.parse_args () The specified parameters in the default are as follows:
Copy the 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 code above adds two option to the program, and when "-V" does not appear, the Opts.verbose preset value is True; when "-Q" is specified, Opts.verbose is set to False, which is a bit 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 default value of the Opts.verbose? The answer is True, and the last option value assigned to the same target will be used.

General option can also be added to the preset value:
Copy the Code code as follows:


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


To add to the program, say:

Most of the standard Unix commands have "-H" and "--help" option, which will be used to print out. By specifying the "help" argument in Optionparser.parse_args () and specifying the specified string, you can add an indication to this option:
Copy the 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 handed over to Optionparser, it automatically prints out the content and ignores the other argument:
Copy CodeThe code is as follows:


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 '


Remember the first reference to the msg_usage of the Optionparser construction? The Optparse Kit also provides some support for usage information. Using the "%prog" keyword in usage, optionparser will automatically replace it with the program name, which is sys.args[0]:
Copy CodeThe code is as follows:


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


If the program is named "Myprog", the usage in the help message will be:
Copy CodeThe code is as follows:


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


If the Optionparser does not receive any parameters, it will automatically produce a usage message:
Copy CodeThe code is as follows:


"Usage:%prog [options]"


The premise is that the program does not have positional argument. Don't worry about the way the option is arranged in the help message, Optionparser will take care of 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.