Examples of how to use Optionparser modules in Python tutorial

Source: Internet
Author: User
In this paper, the use of Optionparser module in Python is described in detail, which has good reference value for learning python in depth. Share it for everyone's reference. The specific analysis is as follows:

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

One is getopt, "deep in Python" also mentioned in the book, can only simple processing 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:  

Add_option is used to add options, action is Store,store_true,store_false, etc., dest is a stored variable, default is the default, help is a helpful hint

Finally, by parsing the Parse_args () function, you get the option, such as the value of 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,    

Now, you can enter it at the command line:

 
  
   
   --file=outfile-q- 
  
   
    
    f outfile--quiet 
   
    
     
     --quiet--file outfile 
    
     
      
      -q-foutfile 
     
      
       
       -qfoutfile 
     
      
    
     
   
    
  
   
 
  

The above commands are the same effect. In addition to this, Optparse also automatically generates command line help information for us:

 
  
   
   -H 
  
   
    
    --help 
  
   
 
  

Output:

Usage: 
 
  
   
   [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 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 the parameter name string and the parameter property. such as-F or –file are the long and short parameter names:

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), 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 of positional arguments.

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.

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

By default, type is ' string '. As shown above, long parameter names are also optional. In fact, 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's parameter name.
The store also has two other forms: Store_true and Store_false, which are used to handle cases with no values after the command line arguments. command-line parameters such as-v,-q:

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:

or use Set_defaults ():

Parser.set_defaults (filename= "Foo.txt", Verbose=true) parser.add_option (...) (options, args) = Parser.parse_args ()

Build program Help

Optparse 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's assist parameter:

Usage = "Usage:%prog [options] arg1 arg2" parser = Optionparser (usage=usage) parser.add_option ("-V", "--verbose",    AC Tion= "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, "    

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

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)-  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 how to generate the Help information in a step-by-step way:

① user-defined program usage information (Usage message):

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]".
② the user does not have to worry about the problem of line breaks when defining the help information for the command line arguments, Optparse will handle all of this.
③ sets the Metavar parameter in the Add_option method to help remind the user of the parameters that the command line parameter 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.

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 these options at your own risk."    

Here are the help information 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:< C10/>caution:use of these options are at your own risk. It is believed that  some of them bite.  -G   

Show Program version

As with the usage message, you can specify its version parameter when you create the Optionparser object, which is used to display the release information for the current program:


In this way, Optparse will automatically interpret the –version command line arguments:

Handling Exceptions

Includes program exceptions and user exceptions. The main discussion here is the user exception, which is the exception that is thrown when 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 USA Ge:foo [Options]  

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:  

In the example above, when the-B and-B command line arguments are present, a "options-a and-b is mutually exclusive" is printed to warn the user.
If the exception handling method above does not meet the requirements, you may need to inherit the Optionparser class and overload 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 (USA GE)  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__":  

It is believed that this article has some reference value to the Python program design of everyone.

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