Python optparser library usage example, pythonoptparser
This article focuses on the optparser library in Python. The details are as follows.
I have never had a special understanding of optparser. Today I am so keen to study this database. Of course, I am not sure I can understand it, but it is enough to cope with normal use. Let's get started with today's sharing.
Introduction
The optparse module is mainly used to pass Command Parameters for scripts.
Introduction
It is very convenient to introduce optparser in IDE.
from optparser import OptionParser
Initialization
We need to pay more attention to initialization.
Because we have two different methods to initialize a parser.
Options with Usage:
The advantage is that it can be used by terminals with help, as shown below:
>>> From optparse import OptionParser >>> usage = "myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..] ">>> parser = OptionParser (usage) # The usage parameter is added to the class.
This will happen when it is displayed.
>>> 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 # customize help information
Options without Usage:
Normally, you do not need to set parameters.
parser = OptionParser()
Add Option
Adding options to the command line is our most important task this time and is also the core. However, before adding options, we should understand why we should add options? How does the option work? In this way, we can better understand the optparser design philosophy.
Option: similar to the Unix operating mode. For example, ls-a or ls-all.
We added an option named all. To simplify the operation, the default value is.
To achieve this effect in OptionParser, we only need to use the following line of code.
# This is just a signal. It does not make sense parser. add_option ('-A',' -- all ')
Core
As the core, it refers to other parameters of add_option. There are several:
- Action: Verify that the input data type matches the type, and store the required parameter in the dest variable. It has the following attributes:
1. Default store value
-Store_false is used together with the store_true below to mark the code and assist in Process Control.
2. store_true flag
- Type: refers to the data type corresponding to parameters such as-f and-n, including string, int, float, etc.
- Dest: used to save temporary variables. Its value can be accessed as an attribute of options. The stored content is the parameter content that is next to, such as-f and-n.
- Help: provides user-friendly help information, which can be used to explain the function description of this add_option method.
Simply speaking, it is boring. Let's take a look at a small example to understand it.
>>> 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'
For the action attribute, see the following code.
>>> 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. parse_args (fakeArgs) >>> options. verboseFalse # If two options v and q are written at the same time, which of the following prevails? The answer is based on the final result >>>> fakeArgs = ['-Q', 'Bye bye ', '-V', 'Hello'] >>> options, args = parser. parse_args (fakeArgs) >>> options. verboseTrue
Non-core
Here we will mainly explain the role of the default parameter, which is actually the default value for dest.
If the dest value is not specified, the default value will be used as the default value of dest!
>>> Parser. add_option ("-x", action = "store", dest = "verbose", default = "defaultvalue") <Option at 0x2d77148:-x >>> options, args = parser. parse_args () # The parameter >>> options. verbose 'defaultvalue'
Complete demo
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 as follows:
File.txt
False
{'Verbose ': False, 'filename': 'file.txt '}
['This is some who', 'arg2', 'arg']
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]
Summary
The above is all the details about the usage of the optparser library in Python. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!