Python method Summary for getting command-line arguments

Source: Internet
Author: User
Describes how python obtains command-line arguments: getopt and Argparse modules.

Python version: 2.7

One, getopt module

The main use of the function in the module:

Options, args = Getopt.getopt (args, shortopts, longopts=[])

Parameter args: generally sys.argv[1:]. Filter out sys.argv[0], which is the name of the execution script, not the command line arguments.

Parameter shortopts: Short format parsing string. For example: "HP:I:", there is no colon after H, which means that there is no argument behind, p and I are followed by a colon, which indicates that the parameter is followed.

Parameter longopts: Long format parsing string list. For example: ["Help", "ip=", "port="],help, there is no equal sign behind it, no argument is followed, IP and port are followed by a colon, which means the parameters are followed.

Return values options are a list of tuples as elements, with each tuple in the form of: (option string, additional parameters), such as: ('-I ', ' 192.168.0.1 ')

The return value of args is a list of elements that do not contain '-' or '-' arguments.

Run the following command at the command line:

Python test_getopt.py-i 192.168.0.1-p 123 A

Or

Python test_getopt.py-ip=192.168.0.1--port=80 123 A

The test_getopt.py code is as follows:

#encoding =utf-8import getoptimport sysdef Main (argv):    try:        options, args = Getopt.getopt (argv, "hp:i:", ["Help "," ip= "," port= "])    except getopt. Getopterror:        sys.exit ()    for option, value in Options:        if option in ("-H", "--help"):            print ("Help")        if option in ("-I", "--ip"):            print ("IP is: {0}". Format (value))        if option in ("-P", "--port"):            print (" Port is: {0} ". Format (value)"    print ("error args: {0}". Format (args)) if __name__ = = ' __main__ ':    Main (sys.argv[ 1:])

The results of the operation are as follows:

Second, Argparse module

Standard module for parsing command-line options and parameters.

Steps to use:

1:import Argparse #导入模块

2:parser = Argparse. Argumentparser () #创建解析对象

3:parser.add_argument () #向该对象中添加使用到的命令行选项和参数

4:parser.parser_args () #解析命令行

Next, the following methods are described in detail Argumentparser and add_argument:

Argumentparser (Prog=none, Usage=none, Description=none, Epilog=none, parents=[], Formatter_class=argparser. Helpformatter, prefix_chars= '-', Fromfile_prefix_chars=none, Argument_default=none, conflict_handler= ' error ', add_ Help=true)

The parameters have default values, which are printed when the program is run because of incorrect parameters or when the Parser.print_help () method is called. It is generally only necessary to pass the parameter description.

Add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest])

The common parameters are explained as follows:

Name or Flags: command-line parameter name or option, such as-P,--port

Action

Store: Default action mode, store value to specified variable

Store_const: Store values specified in the const section of the parameter, commonly used to implement non-Boolean command-line flag

Store_true/store_false: boolean switch. The default value of Store_true is False, which is true if the command line has input of the boolean switch. Store_false opposite

Append: Stores the value to the list, which can be reused

Append_const: Store value to list, store value specified in const part of parameter

Count: Number of inputs for shorthand for statistical parameters

Version: Output release information, and then exit the script

Nargs: The number of command-line arguments, generally denoted by a wildcard:? Represents only one, * represents 0 to more, + represents 1 to more

Default: Defaults

Type: Types of parameters, default to string, or float, int, and BOOL

Choices: Enter a range of values

Required: The default is False, or true to indicate that the parameter must be entered

Help: Helpful Tips for using

Dest: The corresponding variable name of the parameter in the program, such as: Add_argument ("-A", dest= "Code_name"), using Parser.code_name in the script to access the value of the command-line option

The sample script test_argparse.py code is as follows:

1 #encoding =utf-8 2 Import argparse 3 4 def main (args): 5 print ("--address {0}". Format (args.code_address)) #args. A Ddress will error, because the value of dest is specified 6 print ("--flag {0}". Format (Args.flag)) #如果命令行中该参数输入的值不在choices列表中, error 7 print ("--port {0} . Format (args.port) #prot的类型为int类型, if the option is not entered on the command line, the error is 8 print ("-l {0}". Format (Args.log)) #如果命令行中输入该参数 This value is true. Because the alias "--log" is specified for the short format "-L", the program uses Args.log to access 9 if __name__ = = ' __main__ ': one parser = Argparse. Argumentparser (usage= "It's usage tip.", description= "help info.") Parser.add_argument ("--address", default=80, help= "the port number.", dest= "code_address") parser.add_argumen T ("--flag", choices=['. txt ', '. jpg ', '. xml ', '. png '], default= ". txt", help= "the file Type") parser.add_argument ("--p Ort ", Type=int, Required=true, help=" the port number. ") Parser.add_argument ("-L", "--log", Default=false, action= "Store_true", help= "active log info.") + args = Parser.parse_args () main (args)

Run the following command, respectively:

Python test_argparse.py

Python test_argparse.py--port 80

Python test_argparse.py--port--flag apk

Python test_argparse.py--port 80-l

More Python ways to get command-line arguments summary related articles please follow topic.alibabacloud.com!

  • Related Article

    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.