A recent problem is to specify parameters to run a particular process, which is similar to the parameters of some of the commands in Linux, such as Ls-a, why the plus-a option responds. The Optparse module implements a similar function, which is to pass command parameters for the script.
Before using this module, you first need to import the class Optionparser in the module, and then create an instance of it (object):
Copy Code code as follows:
From Optparse import Optionparser
Parser = Optionparser () #这里也可以定义类的参数, followed by
Then you can add the options, basic syntax:
Copy Code code as follows:
Parser.add_option (Opt_str, ...,
Attr=value, ...)
Each OPT_STR can have multiple option strings, such as-F and--file (ls-a and LS--all effects on the line Linux command line), as long as these options are defined, the options are recognized when the command line is entered, or an error is made. The definition of OPT_STR can be as follows:
Copy Code code as follows:
Parser.add_option ("F", "--file", ...) #-f and--file are tags that are used as parameters for the call and are recognized
Once the selected item is defined, you can call the Parse_args () function to get our defined options and parameters
Copy Code code as follows:
(options, args) = Parser.parse_args () #parse_args可以有参数, do not define the words using the default sys.argv[1:]
Parse_args () returns two values, one is option options (such as:-f), and the other is parameter args, which is a value other than option options (such as: Test.txt)
The most important four option attributes in Add_option are: action,type,dest (destination), help. The four action is the most basic.
Action arguments (with the type, dest) are included:
The action parameter tells Optparse what to do when it encounters an option on the command line. Action has three ways of storing: Store, Store_false, Store_true. If you do not specify an action value, the default is the store, which tells Optparse that the next argument (type) will continue to be read, that the type is correct, and that it store the value in a variable (dest), and that the string entered in the command line will save it as a property of the options. This can be called directly. Long-winded a lot of, I have been dizzy ~ ~ ~ ~ ~ ~, First look at an example!
Copy Code code 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 the dest is then stored as a parser property. So, when you call the Parse_args function, the value of the Options.filename is foo.txt. This is stored as "string", and of course the type can also be int and float, such as the following:
Copy Code code as follows:
Parser.add_option ("-N", type= "int", dest= "num")
Note that this option that does not specify a long string (such as:--number), of course, is OK, but the option is only-n when the command line is entered, and no action is specified, using the default store. Use the impersonated command-line argument again ["-n22"] (a parameter) or write ["-N 22"] (passed as two arguments):
Copy Code code 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 a type parameter, the default is string type, so one of the easiest ways to do this is to write:
Copy Code code as follows:
Parser.add_option ("F", dest= "filename")
Action another two values are: "Store_true" and "Store_false", which are typically used as a tag, such as setting flag to True when you start a program, and setting flag to False when you exit. The following example is clear: when an item encounters V, it sets Options.verbose to true, and when the selected item encounters Q, it sets Options.verbose to false:
Copy Code code 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 it is, I tried it, is to the final appearance, 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 the dest, it is presented as follows:
Copy Code code 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 following two sentences have the same effect (provided that the Parse_args () function is not passed to the parameter:)
Copy Code code 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 argument is designed to make our definition of "commands" more realistic and to provide help messages! Oh ~ ~ Simple usage is as follows:
Copy Code code 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 Help")
<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 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 found on the Internet to simulate the command line parameters of the example, the other is "real" example ~ ~ ~
Example1:
Copy Code code 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 results of the operation are:
Copy Code code as follows:
File.txt
False
{' Verbose ': False, ' fileName ': ' File.txt '}
[' This is some what ', ' arg2 ', ' arge ']
usage:myprog[-F <filename>][-s <xyz>] Arg1[,arg2
Options:
-H,--help show this Help and exit
-F FILENAME,--file=filename
-V,--vison make lots of noise [default]
Example2:
A simple example is when you pass the option N to the script, the output is the value of the parameter of n, otherwise the default value is given (the script is saved in E disk):
Copy Code code 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时, use the given parameter value
#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 to run as follows: