Python has two built-in modules for handling command-line arguments:
One is that getopt,getopt can simply handle command-line arguments.
The other is optparse, a Python module that allows programmers to easily design simple, easy-to-use, standard UNIX command-line Programs. Generate usage and help Information.
The following is a simple example script optparse_exampl_1.py:
[email protected] python]# Vim optparse_exampl_1.py
|
#!/usr/bin/env pythonfrom optparse import OptionParserparser = 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() |
You can now enter the following on the command line:
|
<yourscript> --file=outfile -q<yourscript> -f outfile --quiet<yourscript> --quiet --file outfile<yourscript> -q -foutfile<yourscript> -qfoutfile |
The above commands are the same effect. In addition to this, Optparse also automatically generates command line help information for Us:
|
<yourscript> -h<yourscript> --help |
Optparse will print the script options and help information:
|
[[email protected] python]# ./optparse_exampl_1.py -hUsage: optparse_exampl_1.py [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 |
The following is a brief introduction to the usage of optparse: aptparse is quite flexible and powerful in most cases, this article describes common Optparse Usages. To first import the Optionparser class, create a class in the main program:
|
from optparse import OptionParser[...]parser = OptionParser() |
You can now define command-line options, with the basic syntax:
|
parser.add_option(opt_str, ...,attr=value, ...) |
Each option has a string of one or more options, such as-f or--file, and typically each option will have a short option and a long Option. For example:
|
parser.add_option("-f", "--file", ...) |
You can freely define as many short options and as many long options as possible (including 0), but at least one option string as a Whole. finally, Once you have defined all the command-line arguments, call Parse_args () to resolve the Program's command line:
|
(options, args) =parser.parse_args() |
Note: You can also pass a command-line argument list to Parse_args (); otherwise, The default is to use Sys.argv[:1]. Parse_args () returns two Values: options, which is an object (optpars. values), which holds the command-line parameter Value. 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 made up of positional arguments.Learn about option Actions:Action is one of the parameters of the Parse_args () method, which indicates how optparse is handled when resolving to a command-line argument. Actions have a fixed set of values to choose from, The default is ' store ', which means that the command line parameter values are saved in the options Object.
| |
parser.add_option ( "-f" , "--file " , action = "store" , type = string , dest = filename ) args = [ "-f " , "foo.txt" ] (options, Args) = parser.parse_args (args) Print options.filename |
finally, "foo.txt" will be printed Out. When optparse resolves to '-f ', it will continue to parse the following ' Foo.txt ' and then save ' 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 a different value, such as int or float, and so on:
|
parser.add_option("-n", type="int", dest="num") |
Note: This option does not have a long option, and the long option is optional, and if you do not specify the Dest option, the value of the options object is accessed using the command-line parameter Name. The store also has two other forms: stort_true and store_false, which are used to handle cases with no values after command-line options, such as command-line arguments such as-v,-q.
|
parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose") |
In this case, when parsing to '-v ', the options.verbose will be given a True value, and conversely, parsing to '-q ' will be given a value of False.
Other Actions Are:
store_const, append, count, Callback
Default value
The Parse_args () method provides a default parameter that is used to set Defaults. Such as:
|
parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose", default=True) |
or use Set_defaults for example:
|
parser.set_defaults(verbose=True)parser.add_option(...)(options, args) =parser.parse_args() |
Program Generation HelpOptparse Another handy feature is the automatic generation of help information for the Program. You only need to specify the Help information text for 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 resolves to-h or help command-line arguments, the help information for the PARSER.PRINT_HELP () print program is called:
|
Usage: <yourscript> [options] arg1 arg2Options:-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=FILEwrite output to FILE-m MODE, --mode=MODE interaction mode: novice, intermediate, orexpert [default: intermediate] |
(note: when the script prints the help information, it exits without parsing the other option Parameters) to customize the way the program is used:
|
usage ="usage: %prog [options] arg1 arg2" |
This line of information is first printed before the Program's option Information. The%prog,optparse will be replaced by a string of the current program name, such as Os.path.basename. (sys.argv[0]). If the user does not provide custom usage information, optparse will use the default: "usage:%prog [options]". When users define the help for command-line arguments, they don't have to worry about the problem of line breaks, Optparse will handle all This. Setting the Metavar parameter in the Add_option method helps remind the user of the parameters that the command-line argument expects, such as metavar= "mode":
Note: the string in the Metavar parameter automatically becomes UPPERCASE. Use%default to insert the default value of the command-line parameter in the Help information for the assist Parameter. If your program has a lot of command-line arguments, you might want to group them, and you can use optiongroup:
|
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) |
The output is as Follows:
|
Usage: <yourscript> [options] arg1 arg2Options:-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=FILEwrite output to FILE-m MODE, --mode=MODE interaction mode: novice, intermediate, orexpert [default: intermediate]Dangerous Options:Caution: use these options at your own risk. It is believed that someof them bite.-g Group option. |
Complete the Following:
|
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)group = OptionGroup(parser, "Debug Options")group.add_option("-d", "--debug", action="store_true",help="Print debug information")group.add_option("-s", "--sql", action="store_true",help="Print all SQL statements executed")group.add_option("-e", action="store_true", help="Print every action done")parser.add_option_group(group) |
Python optparse Module Learning