Python Argparse Module

Source: Internet
Author: User

Argparse Module

  In Python, the Argparse module is the module used in the standard library to parse command-line parameters to replace obsolete optparse modules. The Argparse module resolves these parameters from the SYS.ARGV according to the definitions in the program and automatically generates help and usage information.

Argumentparse Parser

  When you use Argparse to parse command-line arguments, you first need to create a parser:

Import Argparseparser = Argparse. Argumentparser ()

  The initialization function of the Argumentparser class has several parameters, the more commonly used is description, which is the description of the program, that is, the text in front of the help message.

Add parameter Options

The Add parameter option for an application requires the Add_argument method of the Argrmentparser object, which has the following format:

 Each parameter has the following meanings:

    • Name/flags: The name of the parameter
    • Action: Action When a parameter is encountered, default value when store.
    • Nargs: The number of parameters, can be a specific number, or a "+" or "*" number. Where the "*" number represents 0 or more parameters, the "+" sign represents 1 or more parameters.
    • Const action and Nargs: required constant value
    • Default: Defaults when parameters are not specified
    • Type: Types of parameters
    • Choices: Values allowed for parameters
    • Required: Optional parameters can be omitted
    • Help: Helpful Information for parameters
    • Metavar: The parameter name in the usage description
    • Dest: Parsed parameter name

Action built-in 6 actions:

Store # Saves the parameter value and may first convert the parameter value to another data type. If an action is not explicitly specified, the action is the default. Store_const # Saves a value that is defined as part of the parameter specification, not a value from a parameter resolution. This is typically used to implement a command-line tag that is not a Boolean value. Store_ture/store_false # Save the appropriate Boolean value. These two actions are used to implement a Boolean switch. Append #将值保存到一个列表中. If the argument recurs, multiple values are saved. Append_const #将一个定义在参数规格中的值保存到一个列表中. Version #打印关于程序的版本信息, and then exit
Parsing parameters

 Parsing command-line arguments requires the Parse_args method of the Agrumentparser object, which returns a Namespace object. When you get an object, the value of the parameter can be accessed through the property. Run directly without error due to default value specified

Parser.add_argument ('-host ', action= ' store ', dest= ' server ', default= ' localhost ', help= ' connect to host ') parser.add_ Argument ('-P ', action= ' store ', dest= ' Port ', default= ' 3306 ', help= ' the port to host ') Parser.parse_args () # Parser.parse_ Args () Stored value namespace (port= ' 3306 ', server= ' localhost ')

The action is stored as the Store_true type when storing the value of the Boolean type.

There is another benefit to using Argparse for parameter resolution, which automatically generates help information based on our option definitions. (Automatically append-h option, print help information)

Emulate the MySQL client's command parameters
import argparseparser = Argparse. Argumentparser (description= ' A python-mysql client ') def getparser (): Parser.add_argument ('--host ', action= ' store ', Dest= ' host ', required=true,help= ' connect to host ') parser.add_argument ('-u ', '--username ', action= ' store ', dest= ' user ', required=true,help= ' user for login ') parser.add_argument ('-P ', '--password ', action= ' store ', dest= ' password ', required=true,help= ' Password to use when user connecting to server ') parser.add_argument ('-P ', '--port ', action= ' store ', Dest= ' Port ', default=3306,type=int,help= ' port number to use for connection or 3306 or default ') parser.add_argument ('-V ')     , '--version ', action= ' version ', version= '% (Prog) s 0.1 ') return Parser.parse_args () def main (): parser = Getparser () Conn_args = Dict (host=parser.host,username=parser.user,password=parser.password,port=parser.port) print (Conn_args if __name__ = = ' __main__ ': Main () 

PS: If the port parameter can specify more than one parameter, then you can add nargs= ' + '.

For more detailed use of the method reference, Poke me

  

Python Argparse Module

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.