How to obtain command line parameters in python

Source: Internet
Author: User
This article explains how to use python to obtain command line parameters. This section describes how to obtain command line parameters in python: getopt mode and argparse module.

Python: 2.7

1. getopt module

Mainly used functions in the module:

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

The args parameter is usually sys. argv [1:]. If sys. argv [0] is filtered out, it is the name of the execution script, not a command line parameter.

Shortopts: Short Format analysis string. For example, "hp: I:", h is not followed by a colon, indicating that a parameter is not followed; p and I are followed by a colon, indicating that a parameter is followed.

Longopts: Long Format analysis string list. For example, if ["help", "ip =", "port ="] and "help" are not followed by an equal sign, it means no parameter is followed; ip and port are followed by a colon, this parameter is followed by a parameter.

The returned value options is a list of elements with tuples as follows: (option string, additional parameters), for example: ('-I', '192. 168.0.1 ')

The returned args is a list. the elements in the list are parameters that do not contain '-' or.

Run the following command on the command line:

Python test_getopt.py-I 192.168.0.1-p 80 123

Or

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

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 running result is as follows:

II. argparse module

Standard module used to parse command line options and parameters.

Procedure:

1: import argparse # import Module

2: parser = argparse. ArgumentParser () # Create a parsing object

3: parser. add_argument () # add the command line options and parameters used to this object

4: parser. parser_args () # parse the command line

The following describes in detail the methods 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)

All the parameters have default values. this description is printed when the program is running because the parameters are incorrect or when the parser. print_help () method is called. Generally, you only need to pass the description parameter.

Add_argument (name or flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])

Common parameters are described as follows:

Name or flags: name or option of a command line parameter, such as-p and -- port

Action:

Store: the default action mode. store the value to the specified variable.

Store_const: specifies the storage value in the const part of the parameter. it is often used to implement non-Boolean command line flag.

Store_true/store_false: Boolean switch. The default value of store_true is False. if the Boolean switch is input in the command line, the value is True. Opposite to store_false

Append: store the value to the list. this parameter can be reused.

Append_const: stores the value to the list. the storage value is specified in the const section of the parameter.

Count: The number of input values abbreviated to the statistical parameter.

Version: output the version information and exit the script.

Nargs: number of command line parameters, which are generally expressed as a wildcard :? Indicates that only one instance is used. * indicates 0 to multiple instances, and + indicates 1 to multiple instances.

Default: default value

Type: the parameter type. the default value is 'string'. It can also be float, int, or Boolean.

Choices: input value range

Required: The default value is False. if it is True, this parameter is required.

Help: used help prompt information

Dest: name of the variable corresponding to the parameter in the program, such as add_argument ("-a", dest = "code_name"). parser is used in the script. code_name to access the value of this command line option

The sample script test_argparse.py is as follows:

# Encoding = utf-8import argparsedef main (args): print ("-- address {0 }". format (args. code_address) # args. address will report an error because the dest value print ("-- flag {0}" is specified }". format (args. flag) # if the value entered by this parameter in the command line is not in the choices list, print ("-- port {0}" is returned }". format (args. port) # The type of prot is int. if this option is not entered in the command line, print ("-l {0}" is returned }". format (args. log) # if this parameter is input in the command line, the value is True. Because the alias "-- log" is specified for the short format "-l", args is used in the program. log to access if _ name _ = '_ main _': 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_argument ("-- flag", choices{'.txt ', '.jpg ','. xml ', '.png'], default = ". txt ", help =" the file type ") parser. add_argument ("-- port", 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 commands:

Python test_argparse.py

The above is the details about how to obtain command line parameters in python. For more information, see other related articles in the first PHP community!

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.