Argparse-Command-Line options and parameter resolution

Source: Internet
Author: User

Reprint: http://blog.xiayf.cn/2013/03/30/argparse/


The Argparse module is added to the Python2.7 as an alternative to the optparse. Argparse implementations support features that are not easily added to the optparse and require changes in the backward-incompatible API, so add a new module to the standard library. compared with the optparse phase

The Argparse API is similar to Optparse, and in many cases uses argparse as a simple alternative by updating the class name and method name used. However, there are places where you cannot maintain direct compatibility when adding new features.

You must decide whether or not to upgrade existing programs as appropriate. If you have written additional code to compensate for Optparse limitations, you may want to upgrade your program to reduce the amount of code you need to maintain. If Argparse is available on all deployment platforms, the new program should use Argparse whenever possible. set a parser

The first step in using Argparse is to create a parser object and tell it what parameters it will have. Then when your program is running, the parser can be used to handle command-line arguments.

The parser class is argumentparser. The construction method receives several parameters to set the descriptive information for the program's help text and other global behaviors or settings.

Import argparse
parser = argparse. Argumentparser (description= ' This are a PYMOTW sample program ')
Defining Parameters

Argparse is a comprehensive database of parameter processing. A parameter can trigger a different action, which is specified by the action parameter of the Add_argument () method. Supported actions include saving parameters (either individually or as part of a list), saving a constant value (including special handling of Boolean switch true/False values) when parsing to a parameter, counting the number of times a parameter appears, and invoking a callback function.

The default action is to save the parameter values. In this case, if a type is provided, the parameter value is converted to that type before it is stored. If the dest parameter is supplied, the parameter value is a property named the Dest parameter value in the Namespace object that is returned when the command line argument is resolved. parsing a command line

Once you have defined all the parameters, you can pass a set of parameter strings to Parse_args () to resolve the command line. By default, the parameter is obtained from sys.argv[1:], but you can also pass your own argument list. Options are handled using the GNU/POSIX syntax, so options and parameter values can be mixed in a sequence.

The return value of the Parse_args () is a namespace that contains the arguments passed to the command. The object saves the parameter to its properties, so if your argument dest is "myoption" then you can args.myoption to access the value. Simple Example

The following simple example has 3 different options: A boolean option (-a), a simple string option (-B), and an integer option (-C).

Import argparse

parser = argparse. Argumentparser (description= ' short sample app ')

parser.add_argument (' A ', action= "Store_true", Default=false)
parser.add_argument ('-B ', action= "store", dest= "B")
parser.add_argument ('-C ', action= "store", dest= "C", Type=int)

print Parser.parse_args (['-a ', '-bval ', '-C ', ' 3 '])

There are several ways to pass values to single character options. The above examples use two different forms,-bval and-C Val.

$ python argparse_short.py
Namespace (a=true, b= ' Val ', c=3)

The value associated with ' C ' in the output is an integer, because the program tells Argumentparser to convert the parameter before saving.

The long option name, which has more than one character for the option, is processed in the same way.

Import argparse

parser = argparse. Argumentparser (description= ' Example with long option names '

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.