


Summary of methods for obtaining 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. argparse module
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
Next details Introducing 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 calling the parser.print_help() method, it will Print these descriptions. 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:
1 #encoding=utf-8 2 import argparse 3 4 def main(args): 5 print("--address {0}".format(args.code_address)) #args.address会报错,因为指定了dest的值 6 print("--flag {0}".format(args.flag)) #如果命令行中该参数输入的值不在choices列表中,则报错 7 print("--port {0}".format(args.port)) #prot的类型为int类型,如果命令行中没有输入该选项则报错 8 print("-l {0}".format(args.log)) #如果命令行中输入该参数,则该值为True。因为为短格式"-l"指定了别名"--log",所以程序中用args.log来访问 9 10 if __name__ == '__main__':11 parser = argparse.ArgumentParser(usage="it's usage tip.", description="help info.")12 parser.add_argument("--address", default=80, help="the port number.", dest="code_address")13 parser.add_argument("--flag", choices=['.txt', '.jpg', '.xml', '.png'], default=".txt", help="the file type")14 parser.add_argument("--port", type=int, required=True, help="the port number.")15 parser.add_argument("-l", "--log", default=False, action="store_true", help="active log info.")16 17 args = parser.parse_args()18 main(args)
Run the following commands respectively:
python test_argparse.py
##python test_argparse.py --port 80 --flag apk
python test_argparse.py --port 80 -l
For more python methods to obtain command line parameters and related articles, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
