search
HomeBackend DevelopmentPython TutorialSummary 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:

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)

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
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 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: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 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.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 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.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 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: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 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.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

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 in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

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 by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

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

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

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 new version

SublimeText3 Linux latest version

MantisBT

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

WebStorm Mac version

Useful JavaScript development tools