Example tutorial for using the optionParser module in Python

  • 2020-04-02 13:59:34
  • OfStack

In this paper, the method of using optionParser module in Python is described in detail in the form of an example, which is of great reference value for in-depth learning of Python. Share with you for your reference. Specific analysis is as follows:

In general, Python has two built-in modules for handling command-line arguments:

One is getopt, also mentioned in Deep in python, which simply handles command-line arguments;

The other, optparse, is powerful and easy to use, making it easy to generate standard, unix-posix command-line instructions.

Here's an example:


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 has store, store_true, store_false, etc. Dest is the stored variable, default is the default value, and help is the help prompt

Finally, the parse_args() function is parsed to obtain the value of options, such as options.pdcl.
 
Here is a simple example of using optparse:


from optparse import OptionParser 
[...] 
parser = OptionParser() 
parser.add_option("-f", "--file", dest="filename", 
   help="write report to FILE", metavar="FILE") 
parser.add_option("-q", "--quiet", 
   action="store_false", dest="verbose", default=True, 
   help="don't print status messages to stdout") 
(options, args) = parser.parse_args() 

Now you can type:


<yourscript> --file=outfile -q 
<yourscript> -f outfile --quiet 
<yourscript> --quiet --file outfile 
<yourscript> -q -foutfile 
<yourscript> -qfoutfile 

These commands have the same effect. In addition, optparse automatically generates command line help information for us:


<yourscript> -h 
<yourscript> --help 

Output:


usage: <yourscript> [options] 
 
options: 
 -h, --help  show this help message and exit 
 -f FILE, --file=FILE write report to FILE 
 -q, --quiet  don't print status messages to stdout 

Simple process

First, you must import the OptionParser class to create an OptionParser object:


from optparse import OptionParser 
 
[...] 
 
parser = OptionParser()

Then, use add_option to define the command-line arguments:


parser.add_option(opt_str, ..., 
   attr=value, ...)

Each command line argument is a string of parameter names and parameter properties. For example, -f or the WMD file are the long and short parameter names:


parser.add_option("-f", "--file", ...)

Finally, once you've defined all the command-line arguments, call parse_args() to parse the program's command line:


(options, args) = parser.parse_args()

Note: you can also pass a list of command-line arguments to parse_args(); Otherwise, sys.argv[:1] is used by default.
Parse_args () returns two values:
Options, which is an object (optpars.values), holds command-line parameter Values. As long as you know the command line parameter name, such as file, you can access its corresponding value: options.file.
Args, which is a list of positional arguments.

The Actions

Action is one of the arguments to the parse_args() method, which tells optparse what to do when it parses a command-line argument. Actions has a fixed set of values to choose from. The default is 'store ', which means to save command-line argument values in the options object.

The sample code is as follows:


parser.add_option("-f", "--file", 
   action="store", type="string", dest="filename") 
args = ["-f", "foo.txt"] 
(options, args) = parser.parse_args(args) 
print options.filename

At the end, "foo.txt" will be printed.

When optparse reaches '-f', it continues to parse the 'foo.txt' that follows, and then saves the 'foo.txt' to options.filename. When parser.args() is called, the value of options. Filename is 'foo.txt'.
You can also specify that the type parameter in the add_option() method is some other value, such as int or float:


parser.add_option("-n", type="int", dest="num")

By default, type is 'string'. Also, as shown above, long parameter names are optional. Actually, the dest parameter is also optional. If the dest parameter is not specified, the value of the options object is accessed using the command line parameter name.
There are also two other forms of store: store_true and store_false, which are used to handle cases with no values after command-line arguments. Such as -v,-q command line parameters:


parser.add_option("-v", action="store_true", dest="verbose") 
parser.add_option("-q", action="store_false", dest="verbose") 

This way, options. Verbose will be given True when resolved to '-v', and False when resolved to '-q'.
Other actions values are:
Store_const, append, count, callback.

The default value

The parse_args() method provides a default parameter to set the default value. Such as:


parser.add_option("-f","--file", action="store", dest="filename", default="foo.txt") 
parser.add_option("-v", action="store_true", dest="verbose", default=True) 

Or set_defaults() :


parser.set_defaults(filename="foo.txt",verbose=True) 
parser.add_option(...) 
(options, args) = parser.parse_args()

Build program help

Another handy feature of optparse is to automatically generate help information for programs. You only need to specify the help text for the help parameter of the add_option() method:


usage = "usage: %prog [options] arg1 arg2" 
parser = OptionParser(usage=usage) 
parser.add_option("-v", "--verbose", 
   action="store_true", dest="verbose", default=True, 
   help="make lots of noise [default]") 
parser.add_option("-q", "--quiet", 
   action="store_false", dest="verbose", 
   help="be vewwy quiet (I'm hunting wabbits)") 
parser.add_option("-f", "--filename", 
   metavar="FILE", help="write output to FILE"), 
parser.add_option("-m", "--mode", 
   default="intermediate", 
  help="interaction mode: novice, intermediate, " 
   "or expert [default: %default]") 

When optparse parses the -h or the whelp command-line argument, parser.print_help() is called to print the program's help information:


usage: <yourscript> [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) 
 -f FILE, --filename=FILE 
   write output to FILE 
 -m MODE, --mode=MODE interaction mode: novice, intermediate, or 
   expert [default: intermediate] 

Note: after the help message is printed, optparse will exit, and no more command line arguments will be parsed.
Step by step, the above examples explain how to generate help information:

Custom program usage message:
 
Usage = "usage: %prog [options] arg1 arg2"  
This line of information is printed prior to the program's options information. For %prog, optparse replaces the string with the name of the current program: os.path.basename.(sys.argv[0]).
If the user does not provide custom usage information, optparse defaults to "usage: %prog [options]".
Users do not have to worry about the problem of line breaking when they define the help information of command line parameters. Optparse will handle all of this.
Set the metavar parameter in the add_option method to help remind the user what the command line parameter expects, such as metavar= "mode" :


-m MODE, --mode=MODE 

Note: the string in the metavar parameter is automatically capitalized.
Use %default in the help information of the help parameter to insert the default value of the command line parameter.

If your program has many command-line arguments and you want to group them, use OptonGroup:


group = OptionGroup(parser, ``Dangerous Options'', 
   ``Caution: use these options at your own risk. `` 
   ``It is believed that some of them bite.'') 
group.add_option(``-g'', action=''store_true'', help=''Group option.'') 
parser.add_option_group(group) 

Here's the help that will be printed:


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' 
 
 Dangerous Options: 
 Caution: use of these options is at your own risk. It is believed that 
 some of them bite. 
 -g   Group option. 

Display program version

Like the usage message, you can specify the version parameter when you create the OptionParser object to display the version information of the current program:


parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") 

 
In this way, optparse automatically interprets the copyversion command-line parameter:


$ /usr/bin/foo --version 
foo 1.0 

Handle exceptions

Includes program exceptions and user exceptions. The focus here is on user exceptions, which are exceptions thrown because the user entered invalid, incomplete command line arguments. Optparse automatically detects and handles some user exceptions:


$ /usr/bin/foo -n 4x 
usage: foo [options] 
 
foo: error: option -n: invalid integer value: '4x' 
 
$ /usr/bin/foo -n 
usage: foo [options] 
 
foo: error: -n option requires an argument 

Users can also customize the handling of partial exceptions by using the parser.error() method:


(options, args) = parser.parse_args() 
[...] 
if options.a and options.b: 
 parser.error("options -a and -b are mutually exclusive") 

In the above example, when both -b and -b command-line arguments exist, "options-a and -b are mad exclusive" is printed to warn the user.
If the above exception handling methods are not enough, you may need to inherit the OptionParser class and override the exit() and erro() methods.

The complete program example is as follows:


from optparse import OptionParser 
[...] 
def main(): 
 usage = "usage: %prog [options] arg" 
 parser = OptionParser(usage) 
 parser.add_option("-f", "--file", dest="filename", 
   help="read data from FILENAME") 
 parser.add_option("-v", "--verbose", 
   action="store_true", dest="verbose") 
 parser.add_option("-q", "--quiet", 
   action="store_false", dest="verbose") 
 [...] 
 (options, args) = parser.parse_args() 
 if len(args) != 1: 
 parser.error("incorrect number of arguments") 
 if options.verbose: 
 print "reading %s..." % options.filename 
 [...] 
 
if __name__ == "__main__": 
 main() 

I believe that this article has some reference value for your Python programming.


Related articles: