Introduction to the optparse Module
Recently, a problem occurs when you specify parameters to run a specific process. This is similar to the parameters of some commands in Linux, such as LS-A. Why does the-A option respond when it is added. The optparse module Implements similar functions. It transmits command parameters for scripts.
Before using this module, you must first import the optionparser class in the module, and then create an instance (object) of it ):
From optparse import optionparserparser = optionparser () # You can also define class parameters here.
Then you can add options. Basic Syntax:
parser.add_option(opt_str, ...,
attr=value, ...)
Each opt_str can have multiple option strings, such as-F and -- file (the results of LS-A and LS-all in the Linux Command Line are the same). If you define these options, these options are identified when you enter the command line. Otherwise, an error is returned. Opt_str can be defined as follows:
Parser. add_option ("-F", "-- file",...) #-F and -- file are tags of parameters used for calling and will be recognized
After the options are defined, you can call the parse_args () function to obtain the defined options and parameters.
(Options, argS) = parser. parse_args () # parse_args can have parameters. If not defined, use the default SYS. argv [1:]
Parse_args () returns two values, one being option options (for example,-F) and the other being the ARGs parameter (for example, test.txt)
The four most important attributes of add_option are action, type, DEST (destination), and help. Actions are the most basic among the four.
Action Parameters(Type and DEST are introduced):
The action parameter tells optparse what to do when it encounters an option in the command line. Action has three storage methods: store, store_false, and store_true. If the action value is not specified, the default value is store, which tells optparse to continue reading the next parameter (type) to ensure the correctness of the type, store the value in a variable (DEST), that is, the string entered in the command line saves it as the attribute of options, which can be called directly. I am dizzy with a bunch of worships ~~~~, Let's look at an example first!
>>> Parser. add_option ("-F", "-- file", Action = "Store", type = "string", DEST = "FILENAME") <option at 0x2d72f48: -F/-- file >>>> ARGs = ["-F", "foo.txt"] # simulate command line Input >>>> (options, argS) = parser. parse_args (ARGs) >>> options.filename'foo.txt'
Above: When optparselooks at example-F, it will be followed by another example of foo.txt and stored in options. filename (this filename is the Dest in add_option). Then the value of DeST will be stored as the property of parser. So when parse_argsparameters are used, the value of options.filenameis foo.txt. This is stored as a "string" type. Of course, the type can also be Int or float, for example:
parser.add_option("-n", type="int", dest="num")
Note: This does not specify a long string option (for example, -- number). This is certainly acceptable, but the option can only be-N when you input the command line, no action is specified, and the default "Store" is used ". You can use the simulated command line parameter ["-n22"] (one parameter) again or ["-N 22"] (passed as two parameters ):
>>> parser.add_option("-n", type="int", dest="num")<Option at 0x2d71308: -n>>>> (options, args) = parser.parse_args(["-n22"])>>> print options .num22
If the type parameter is not specified, the default type is string, so the simplest method can be written as follows:
parser.add_option("-f", dest="filename")
The other two values of action are "store_true" and "store_false", which are generally used as a tag. For example, when a program is started, flag is set to true, set flag to false when exiting. After reading the following example, it is completely clear: when Option V is encountered, it sets options. verbose to true. When option Q is encountered, it sets options. verbose to false:
>>> 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. verbosetrue >>> fakeargs = ['-Q', 'Bye bye'] >>> options, argS = parser. par Se_args (fakeargs) >>> options. verbosefalse # If you write two options V and Q at the same time, which of the following prevails? I tried it and the last one prevails. Fakeargs = ['-Q', 'Bye bye','-V', 'Hello'] >>> options, argS = parser. parse_args (fakeargs) >>> options. verbosetrue
Default parameter:
The default parameter is well understood, that is, when the Dest value is not specified, a default value is given, as shown below:
>>> Parser. add_option ("-X", Action = "Store", DEST = "verbose", default = "HAHAHA") <option at 0x2d77148:-x >>> options, ARGs = parser. parse_args () # The parameter >>> options. verbose 'hahahahaha'
In this case, the effect of the following two statements is the same (provided that the parameter is not passed to the parse_args () function :)
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 used to make the defined "command" more realistic and provides help messages! Haha ~~ The simple usage is as follows:
>>> From optparse import optionparser >>> usage = "myprog [-F <FILENAME>] [-S <XYZ>] arg1 [, arg2..] ">>> parser = optionparser (usage) # The usage parameter is added here. >>> optparser. add_option ("-F", "-- file", Action = "Store", type = "string", DEST = "FILENAME", help = "no any help ") <option at 0x2bdb888:-F/-- file >>>> fakeargs = letter '-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 # The two rows are automatically generated based on option, which is intelligent ~~ -F filename, -- file = filename no any help # This is the help information I defined (haha, not very friendly ~~) >>> Parser. print_usage () usage: myprog [-F <FILENAME>] [-S <XYZ>] arg1 [, arg2..] # This is the usage information of the class ~~ It's very lifelike. What is it? >>>
The above describes the basic syntax. Here are two examples: one is an example of simulating command line parameters on the Internet, and the other is a "real" example ~~~
Example1:
from optparse import OptionParserusage = "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.fileNameprint options.verboseprint optionsprint argsprint optParser.print_help()
The running result is:
file.txtFalse{'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 message and exit -f FILENAME, --file=FILENAME -v, --vison make lots of noise [default]
Example2:
A simple example is to output the value of N parameter when option n is passed to the script. Otherwise, the default value is given (the script is saved on the E disk ):
From optparse import optionparseroptparser = optionparser () optparser. add_option ("-n", "-- number", Action = "Store", type = "int", DEST = "intnumber") optparser. add_option ("-V", "-- version", Action = "store_false", DEST = "verbose", default = 'gggggggggggg', help = "no help") options, ARGs = optparser. parse_args () If options. intnumber is not none: # When option n is available, use the given parameter value # num = options. intnumber Print Options. intnumber, options. V Erboseelse: for I in range (): # If option n is not given, the default output is 1 ~ 4 # num = I print I
Run the following command on CMD: