Python module learning-optparse, python module optparse
The optparse built-in module is used to process Python command line parameters.
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 parameters:
- Parser. add_option (opt_str ,...,
- Attr = value ,...)
Each command line parameter is composed of a parameter name string and parameter attributes. For example-FOr-FileThe parameter names are respectively long and short:
- Parser. add_option ("-f", "-- file ",...)
Finally, once you have defined all the command line parameters, call parse_args () to parse the program's command line:
- (Options, args) = parser. parse_args ()
Example
The following 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 ()