Home Backend Development Python Tutorial Summary of methods for obtaining command line parameters in Python

Summary of methods for obtaining command line parameters in Python

Mar 08, 2017 am 10:09 AM

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:])
Copy after login

The running results are as follows:

Summary of methods for obtaining command line parameters in Python

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)
Copy after login

Run the following commands respectively:

python test_argparse.py

Summary of methods for obtaining command line parameters in Python

##python test_argparse.py --port 80

Summary of methods for obtaining command line parameters in Python##python test_argparse.py --port 80 --flag apk

Summary of methods for obtaining command line parameters in Pythonpython test_argparse.py --port 80 -l

Summary of methods for obtaining command line parameters in Python

For more python methods to obtain command line parameters and related articles, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1245
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

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.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

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.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

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 vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

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 vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

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.

See all articles