


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!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

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...

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


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools