Python opt parse module (using opt parse to process command line parameters) __python

Source: Internet
Author: User

Python has two built-in modules to handle command-line arguments, one is getopt, and the Deep in
Python is also mentioned in the book, can only handle command-line parameters, the other is Optparse, it is powerful, and easy to use, can easily generate standard, compliant
Command line description for the UNIX/POSIX specification.
Example

Here is a simple example of using Optparse:

From Optparse import Optionparser
[...]
Parser = Optionparser ()
Parser.add_option ("F", "--file", dest= "filename",
help= "Write 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 enter at 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

Output:

Usage: <yourscript> [options]

Options
-H,--help show this Help and exit
-F FILE,--file=file write to File
-Q,--quiet don ' t print status messages to stdout

Simple process

First, you must import the Optionparser class and create a 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 consists of a parameter name string and an argument property. such as-f or? File is the name of the short parameter:

Parser.add_option ("F", "--file", ...)

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].

Two values returned by Parse_args ():

* Options, it is an object (Optpars). Values), with the command line argument value saved. As long as you know the command line argument name, such as file, you can access its corresponding value: Options.file.
* args, which is a list of arguments made up of positional.

Actions

The action is one of the parameters of the Parse_args () method, which indicates how the Optparse is handled when parsing to a command-line argument. The actions have a fixed set of values to choose from, and the default is ' store ', which means that the command line parameter values are saved in the Options object.

Example

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, the "Foo.txt" will be printed out.

When optparse resolves to '-f ', it continues parsing the ' foo.txt ' and then saves ' foo.txt ' to options.filename. When Parser.args () is invoked, the Options.filename value 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")

By default, type is ' string '. Also, as indicated above, long parameter names are optional. In fact, the dest parameter is optional. If the Dest parameter is not specified, the value of the options object is accessed using the parameter name of the command line.

The store also has two other forms: Store_true and Store_false, which are used to handle situations with no values following the command line arguments. 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 ', Options.verbose will be given a True value, whereas parsing to ' Q ' will be given a value of False.

Other actions are as follows:

Store_const, append, Count, callback.
Default value

The Parse_args () method provides a default parameter for setting defaults. 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 use 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 the automatic generation of Help information for programs. You only need to specify the Help message 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]")

The Help information for the PARSER.PRINT_HELP () print program is invoked when the Optparse resolves to the-H or the? Assist command-line argument:

Usage: <yourscript> [options] arg1 arg2

Options
-H,--help show this Help 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 printing out the Help information, Optparse will exit and no longer resolve other command-line arguments.

Use the example above to explain step-by-step how to generate help information:

*

Custom program use method information (usage message):

Usage = "Usage:%prog [options] arg1 arg2"

This line of information is printed prior to the program's option information. The%prog,optparse in this case is replaced by the 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 a user defines the help for a command-line parameter, don't worry about the line-wrapping problem, Optparse will handle it all.
*

Setting the Metavar parameter in the Add_option method helps to remind the user that the parameters expected by this command-line parameter, such as metavar= "mode":

-M MODE,--mode=mode

Note: The string in the Metavar parameter automatically becomes uppercase.
*

Use%default to insert the default value of the command-line parameter in 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 Optongroup:

Group = OptionGroup (parser, ' dangerous Options ',
' Caution:use 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 are the help messages that will be printed:

Usage: [Options] Arg1 arg2

Options
-H,--help show this Help 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 are at your own risk. It is believed that
Some of them bite.
-G Group option.

Show Program version

Like usage message, you can specify its version parameter when creating a Optionparser object to display the current program's versioning information:

Parser = Optionparser (usage= "%prog [-f] [Q]", version= "%prog 1.0")

This way, Optparse will automatically explain the version command-line arguments:

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

Handling Exceptions

Includes program exceptions and user exceptions. The main discussion here is the user exception, which is the exception that is thrown because the user enters an invalid, incomplete command-line argument. Optparse can automatically detect and handle 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 use the Parser.error () method to customize the handling of partial exceptions:

(options, args) = Parser.parse_args ()
[...]
If OPTIONS.A and options.b:
Parser.error ("Options-a and-b are mutually exclusive")

In the example above, when the-B and-B command-line arguments are present, the "options-a And-b are mutually exclusive" is printed to warn the user.

If the above exception handling method does not meet the requirements, you may need to inherit the Optionparser class and overload the exit () and Erro () methods.
Complete program Examples

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 ()

Reference: http://docs.python.org/lib/module-optparse.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.