Examples of how to use Optionparser modules in Python tutorial _python

Source: Internet
Author: User
Tags exception handling in python

This paper describes the use of Optionparser module in Python in detail, and it has good reference value for studying python in depth. Share for everyone to use for reference. The specific analysis is as follows:

In general, there are two built-in modules in Python that handle command-line arguments:

One is getopt, "Deep in Python" also mentions that only simple processing of command-line parameters;

The other is Optparse, which is powerful and easy to use, and makes it easy to generate standard, UNIX/POSIX-compliant command-line instructions.

Examples are as follows:

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 is Store,store_true,store_false, dest is stored variables, default is defaults, Help is helpful tips

Finally, the Parse_args () function is parsed to obtain the option, such as the OPTIONS.PDCL value.

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 message 
 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, respectively, are the names of short and long parameters:

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 positional arguments.

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.

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

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]") 

When optparse resolves to-h or –help command-line arguments, the help information for the PARSER.PRINT_HELP () print program is invoked:

Usage: <yourscript> [options] arg1 arg2 
 
options:- 
 H,--help Show this help  and exit 
 -V,--v Erbose make  lots of noise [default]- 
 Q,--quiet be  vewwy quiet (I ' m hunting wabbits)- 
 f FILE,--filename=f ILE 
   Write output to FILE- 
 m MODE,--mode=mode interaction mode:novice, intermediate, or 
   expert [default:in Termediate] 

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 users are defining help for command-line arguments, Optparse will handle all this without worrying about line-wrapping problems.
③ sets the Metavar parameter in the Add_option method to help 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. ') ' 
   It is risk Ved 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 message 
 and Exit-V,--verbose make lots of Noise [Default] 
 -Q,--quiet is  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:< C11/>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") 


In this way, Optparse automatically interprets 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.

The complete program examples are 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 () 

It is believed that this article has certain reference value to everyone's Python programming.

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.