Command line parameter passing (command line parsing)

 1. The role of command line parameter passing

Command line argument passing provides a variety of benefits to programs, including:

  1. Flexibility: Through command line parameters, users can change the behavior of the program every time they run it without modifying the code.

  2. Automation and batch processing: Command line parameters make it easier for scripts and programs to be called by automation tools, batch files, or other scripts, passing different parameters.

  3. Simplified configuration: For some simple programs or tasks, using command line parameters may be more intuitive and simpler than creating and reading configuration files.

  4. Real-time help documentation: Using a library likeargparse, you can provide a description for each parameter so that when the user needs help, They can obtain parameter information directly on the command line.

  5. Portability: Command line parameters have consistent concepts and behavior across different operating systems and environments, which increases code portability.

  6. Explicitness: When launching a program from the command line and supplying arguments, explicitly specifying argument values ​​can make the operation more transparent, which can be very helpful for logging and troubleshooting .

  7. Rapid prototyping and testing: During the development phase, programmers can quickly run the program and use different parameters to test different scenarios or functions.

  8. Reduce errors: By setting type and validity checks on command line parameters, as provided by theargparse library, you can ensure that user-supplied input are legal and expected, thus reducing runtime errors.

  9. Integration with other tools: Many modern development, deployment, and monitoring tools utilize command line interfaces to operate. Command line arguments provide a standardized way that your program or script can integrate seamlessly with these tools.

2. A simple case

A simple example is provided below to demonstrate how to useargparse。

Let's say we have a script that takes two parameters: one is a name and the other is an age, and we want to print a welcome message.

Script content (greet.py):

import argparse


def main():
    # 创建解析器对象
    parser = argparse.ArgumentParser(description='简单的问候脚本')

    # 添加姓名和年龄参数
    parser.add_argument('--name', type=str, required=True, help='你的姓名')
    parser.add_argument('--age', type=int, required=True, help='你的年龄')

    # 解析参数
    args = parser.parse_args()

    # 打印欢迎消息
    print(f"你好,{args.name}!你已经{args.age}岁了。")


if __name__ == '__main__':
    main()

How to run:cd to the directory where the script is located, and then from the command line, you can call the script and pass the parameters like this: 

python greet.py --name 张三 --age 25

After running, you will see the output:

你好,张三!你已经25岁了。

 Right now:

3. Detailed explanation of usage examples of argparse module

The argparse module is a command line option, argument and subcommand parser. Makes it easy to write user-friendly command line interfaces. Suitable for situations where the code needs to modify parameters frequently.

Common usage examples of python's argparse module include examples (super detailed)_python argparse usage examples-CSDN blog

Usage ideas:

1) First import the argparse module import argparse
2) Create an ArgumentParser object, which contains all the functions required to parse command line input into Python data. description is the description information of the object, which can be viewed using the python test_argparse.py -h command
parser = argparse.ArgumentParser(description='Calculate volume of a cylinder') () is the parameter name in turn; parameter type, declare the data type of this parameter to be int. In order to participate in the operation, the default data type is str; description information parser.add_argument('radius', type=int, help='Radius of cylinder')
3) Add the command line parameters that need to be entered 5) Pass the obtained radius and height args.radius, args.height as parameters to the method to get the result




 

Guess you like

Origin blog.csdn.net/m0_55196097/article/details/133324102