Analysis of Optparse module usage in python

Source: Internet
Author: User

Reprint: http://www.jb51.net/article/59296.htm

Recently encountered a problem is to specify parameters to run a particular process, which is very similar to some of the parameters of Linux commands, such as ls-a, why the plus-a option will respond. The Optparse module implements a similar function, which is to pass command parameters to the script.

Before using this module, you first need to import the class Optionparser in the module and then create an instance (object) of it:

Copy CodeThe code is as follows:
From Optparse import Optionparser
Parser = Optionparser () #这里也可以定义类的参数, followed by

Then you can add the options, the basic syntax:

Copy CodeThe code is as follows:
Parser.add_option (Opt_str, ...,
Attr=value, ...)
Each OPT_STR can have multiple option strings, such as-F and--file (as in the line Linux command line ls-a and LS--all), as long as these options are defined, the options are recognized at the command line, or an error is made. The definition of OPT_STR can be as follows:
Copy CodeThe code is as follows:
Parser.add_option ("-F", "--file", ...) #-f and--file are the tags that are used as parameters of the call and are recognized
Once the selected item is defined, you can call the Parse_args () function to get the options and parameters we define
Copy CodeThe code is as follows:
(options, args) = Parser.parse_args () #parse_args可以有参数, if not defined, use the default sys.argv[1:]
Parse_args () returns two values, one is option options (e.g.-f), and the other is the parameter args, which is a value other than option options (e.g. Test.txt)

The most important four option attributes in Add_option are: action,type,dest (destination), help. These four action are the most basic.

The action parameter (type, dest is included):

The action parameter tells Optparse what to do when it encounters an option on the command line. There are three ways to store action: Store, Store_false, Store_true. If you do not specify the value of the action, the default is store, which tells Optparse to continue reading the next parameter (type), to guarantee the correctness of the type, and to store it in a variable (dest), and to save it as a property of the options in the string entered on the command line. This can be called directly. A lot of wordy, I myself have been dizzy ~ ~ ~, First look at an example!

Copy CodeThe code is as follows:
>>> parser.add_option ("-F", "--file", action= "store", type= "string", dest= "filename")
< Option at 0x2d72f48:-f/--file>
>>> args = ["-F", "foo.txt"] #这个是模拟命令行的输入
>>> (options, args) = Parser.parse_args (args)
>>> Options.filename
' Foo.txt '

Above: When Optparse sees option-F, it will continue to read the next parameter is Foo.txt, and store it in Options.filename (this filename is dest in add_option), The value of dest is then stored as the parser property. So, when the Parse_args function is called, the value of Options.filename is foo.txt. This is stored as a "string" type, of course type can also be int and float, such as the following:

Copy CodeThe code is as follows:
Parser.add_option ("-N", type= "int", dest= "num")
Note that this does not specify an option for a long string (for example:--number), which of course is OK, but the command line input option is only n, and no action is specified, using the default "store". Using the simulated command-line arguments again ["-n22"] (a parameter) can also be written as ["-N 22"] (passed as two parameters):
Copy CodeThe code is as follows:
>>> parser.add_option ("-N", type= "int", dest= "num")
< Option at 0x2d71308:-n>
>>> (options, args) = Parser.parse_args (["-n22"])
>>> print options. num
22

If you do not specify the type parameter, the default is a string type, so the simplest way to do this is to write:

Copy CodeThe code is as follows:
Parser.add_option ("-F", dest= "filename")

Action two other values are: "Store_true" and "Store_false", which are generally used as a token, such as setting flag to True when starting a program, and setting flag to false when exiting. See the following example is fully understood: when the election encounters V, it sets Options.verbose to true, when the selected item encounters Q, it sets Options.verbose to false:

Copy CodeThe code is as follows:
>>> from Optparse import Optionparser
>>> Parser=optionparser ()
>>> parser.add_option ("-V", action= "Store_true", dest= "verbose")
< Option at 0x2ceb888:-v>
>>> parser.add_option ("-Q", action= "Store_false", dest= "verbose")
< Option at 0x2d68e48:-q>
>>> Fakeargs = ['-V ', ' hello ']
>>> options, args = Parser.parse_args (Fakeargs)
>>> Options.verbose
True
>>> Fakeargs = ['-Q ', ' Bye Bye ']
>>> options, args = Parser.parse_args (Fakeargs)
>>> Options.verbose
False
#如果同时写两个选项v和q, it will be whichever, I tried, is the final appearance of the prevail, hehe ~ ~
>>> Fakeargs = ['-Q ', ' Bye Bye ', '-V ', ' hello ']
>>> options, args = Parser.parse_args (Fakeargs)
>>> options. Verbose
True

Default parameter:

The default parameter is well understood, that is, when you do not specify a value for Dest, the defaults are given, as follows:

Copy CodeThe code is as follows:
>>> parser.add_option ("-X", action= "store", dest= "verbose", default= "hahaha")
< Option at 0x2d77148:-x>
>>> options, args = Parser.parse_args () #这里没有传参数
>>> Options.verbose
' Hahaha '
If so, the effect of the following sentence is the same (provided that the Parse_args () function is not passed:)
Copy CodeThe code is as follows:
Parser.add_option ("-V", action= "Store_true", dest= "verbose")
Parser.add_option ("-Q", action= "Store_false", dest= "verbose", default=true)

Help parameters:

This parameter is designed to make the "command" we define more realistic and provides a help message! Oh ~ ~ Simple usage is as follows:

Copy CodeThe code is as follows:
>>> from Optparse import Optionparser
>>> usage = "myprog[-f <filename>][-s <xyz>] arg1[,arg2 ...]"
>>> parser=optionparser (usage) #这里为类添加了参数usage
>>> optparser.add_option ("-F", "--file", action = "store", type= "string", Dest = "FileName", help= "no any")
< Option at 0x2bdb888:-f/--file>
>>> Fakeargs = ['-F ', ' file.txt ']
>>> options, args = Parser.parse_args (Fakeargs)
>>> Options.filename
' File.txt '
>>> Parser.print_help ()
usage:myprog[-F <filename>][-s <xyz>] arg1[,arg2 ...]

Options:
-H,--help show this help message and exit #此两行根据option自动生成, compare Smart Amount ~ ~
-F FILENAME,--file=filename
No any help #这是我定义的帮助信息 (hehe, not very friendly ~ ~)
>>> Parser.print_usage ()
usage:myprog[-F <filename>][-s <xyz>] arg1[,arg2 ...] #这是类的usage信息 ~ ~ Very lifelike, have wood?

>>>


The above is to introduce the basic syntax, the following two examples, one is the online search for an example of the parameters of the command line, the other is "real" example ~ ~ ~

Example1:

Copy CodeThe code is as follows:
From Optparse import Optionparser
Usage = "myprog[-f <filename>][-s <xyz>] arg1[,arg2 ...]"
Optparser = Optionparser (usage)
Optparser.add_option ("-F", "--file", action = "store", type= "string", Dest = "FileName")
Ooptparser.add_option ("-V", "--vison", action= "Store_false", dest= "verbose", default= ' None ',
Help= "Make lots of noise [default]")
Fakeargs = ['-F ', ' file.txt ', '-V ', ' Good luck to you ', ' arg2 ', ' arge ']
Options, args = Optparser.parse_args (Fakeargs)
Print Options.filename
Print Options.verbose
Print options
Print args
Print Optparser.print_help ()

The operating result is:

Copy CodeThe code is as follows:
File.txt
False
{' Verbose ': False, ' fileName ': ' File.txt '}
[' This was some what ', ' arg2 ', ' arge ']
usage:myprog[-F <filename>][-s <xyz>] arg1[,arg2 ...]
Options:
-H,--help show this help message and exit
-F FILENAME,--file=filename
-V,--vison make lots of noise [default]

Example2:

A simple example is that when you pass the option N to the script, the output is the value of the n parameter, otherwise the default value is given (the script is saved in the E-drive):

Copy CodeThe code is as follows:
From Optparse import Optionparser
Optparser = Optionparser ()
Optparser.add_option ("-N", "--number", action = "store", type= "int", dest = "intnumber")
Optparser.add_option ("-V", "--version", action= "Store_false", dest= "verbose", default= ' gggggggg ', help= "no Help")
Options, args = Optparser.parse_args ()
If Options.intnumber is not None: #当有选项n时, the given parameter value is used
#num = Options.intnumber
Print Options.intnumber,options.verbose

Else
For I in range (1,5): #不给选项n的情况下, the default output is 1~4
#num = i
Print I

Open cmd Run as follows:

Analysis of Optparse module usage in python

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.