Home > Article > Backend Development > How to get command line parameters in python
Introducing python's method of obtaining command line parameters: getopt module and argparse module.
Python version: 2.7
1. getopt module
Mainly uses the functions in the module:
options, args = getopt.getopt(args, shortopts, longopts=[])
Parameter args: usually sys.argv[1:]. Filter out sys.argv[0], which is the name of the executed script and is not counted as a command line parameter.
Parameter shortopts: short format analysis string. For example: "hp:i:", there is no colon after h, which means there are no parameters; there are colons after p and i, which means there are parameters.
Parameter longopts: long format analysis string list. For example: ["help", "ip=", "port="], there is no equal sign after help, which means there are no parameters; there is a colon after ip and port, which means there are parameters.
The return value options is a list with tuples as elements. The form of each tuple is: (option string, additional parameters), such as: ('-i', '192.168.0.1')
The return value args is a list, the elements of which 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 a
or
python test_getopt.py -ip=192.168.0.1 --port=80 123 a
test_getopt.py code is as follows:
#encoding=utf-8 import getopt import sys def 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 results are as follows:
2. The argparse module
is a standard module used to parse command line options and parameters.
Usage steps:
1: import argparse #Import module
2: parser = argparse.ArgumentParser() #Create parsing object
3: parser .add_argument() #Add the command line options and parameters used to the object
4: parser.parser_args() #Parse the command line
The following is a detailed introduction to 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)
The parameters have default values. When running the program due to incorrect parameters or when the parser.print_help() method is called, these description information will be printed. Generally, only the parameter description needs to be passed.
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: The default action mode, stores the value to the specified variable
Store_const: The storage value is specified in the const part of the parameter, often used to implement non-Boolean command line flags
store_true/store_false: Boolean switch. The default value of store_true is False. If the Boolean switch is entered on the command line, the value is True. The opposite of store_false
Append: Store the value into the list, this parameter can be reused
Append_const: Store the value into the list, the stored value is specified in the const part of the parameter
count: Statistics The number of input parameter abbreviations
Version: Output version information, and then exit the script
nargs: The number of command line parameters, generally represented by wildcards: ? means only one is used, * means 0 to more, + means 1 to more
default: Default value
type: The type of parameter, the default is string type, it can also be float, Types such as int and Boolean
choices: the range of input values
required: the default is False, if True, it means that the parameter must be entered
help: the help prompt used Information
dest: The corresponding variable name of the parameter in the program, such as: add_argument("-a", dest="code_name"), use 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:
#encoding=utf-8 import argparse def main(args): print("--address {0}".format(args.code_address)) #args.address会报错,因为指定了dest的值 print("--flag {0}".format(args.flag)) #如果命令行中该参数输入的值不在choices列表中,则报错 print("--port {0}".format(args.port)) #prot的类型为int类型,如果命令行中没有输入该选项则报错 print("-l {0}".format(args.log)) #如果命令行中输入该参数,则该值为True。因为为短格式"-l"指定了别名"--log",所以程序中用args.log来访问 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 respectively:
python test_argparse.py
python test_argparse.py --port 80
python test_argparse.py --port 80 --flag apk
python test_argparse.py --port 80 -l
The above is the detailed content of How to get command line parameters in python. For more information, please follow other related articles on the PHP Chinese website!