python 命令行参数 argparse详解

2023-12-13 10:57:19

完整模板

首先,直接给出完整的使用,有以下模板方便直接套用,以读入命令行参数:

def parse_command_line_arguments():
    # Import the required modules
    import argparse
    # Instantiate the parser
    command_line_arguments_parser = argparse.ArgumentParser()

    # TODO: ADD YOUR ARGUMENTS HERE

    # Add positional arguments
    command_line_arguments_parser.add_argument(
        "my_positional_int_arg",
        type=int,
        help="This is a essential test integer argument",
        default=3,
    )

    # Add optional arguments
    command_line_arguments_parser.add_argument(
        "--my_optional_string",
        type=str,
        help="This is a optional test string argument",
        default="hello world",
    )

    # Add bool arguments(no argument value needed)
    command_line_arguments_parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="When True, prints out more information",
    )

    # Parse the arguments
    command_line_args = command_line_arguments_parser.parse_args()

    # Return the parsed arguments
    return command_line_args

    # TODO: USE IN YOUR CODE
    # command_line_args = parse_command_line_arguments()
    # print(command_line_args.your_argument_name)

在主代码中使用的参考如下:

command_line_args = parse_command_line_arguments()

# Print all arguments
print(command_line_args)

# Int arguments usage
print(f"Squared value of {command_line_args.my_positional_int_arg} is {command_line_args.my_positional_int_arg**2}")

# Bool arguments usage
if command_line_args.verbose:
    print("This is a verbose print when --verbose is True")

具体解释

对于模板中存在的代码片段,有如下解释:

基本使用

# Import the lib
import argparse
# Instantiate the parser
command_line_arguments_parser = argparse.ArgumentParser()
# Parse the arguments
command_line_args = command_line_arguments_parser.parse_args()

此时无任何程序所需的参数需要输入,通过python <your_script>.py -h进行检验,应当输出如下:

hermanye@hermanye:~/test_ws$ python my_test.py -h
usage: my_test.py [-h]

optional arguments:
  -h, --help  show this help message and exit

添加参数

在实例化ArgumentParser后,使用add_argument()添加需要读取的参数,并指定它的名称、提示说明、参数变量类型、动作等。

位置参数

对于必须要输入的位置参数:

  • 片段
# Add positional arguments
command_line_arguments_parser.add_argument(
    "my_positional_int_arg",
    type=int,
    help="This is a essential test integer argument",
    default=3,
)
  • 示例代码
# Import the lib
import argparse
# Instantiate the parser
command_line_arguments_parser = argparse.ArgumentParser()
# Add positional arguments
command_line_arguments_parser.add_argument(
    "my_positional_int_arg",
    type=int,
    help="This is a essential test integer argument",
    default=3,
)
# Parse the arguments
command_line_args = command_line_arguments_parser.parse_args()
# Print all arguments
print(command_line_args)
# Int arguments usage
print(f"Squared value of {command_line_args.my_positional_int_arg} is {command_line_args.my_positional_int_arg**2}")
  • 测试
python my_test.py 5
# Results
Namespace(my_positional_int_arg=5)
Squared value of 5 is 25

可选参数

对于可选参数,需要在参数名前加上--

  • 片段
# Add optional arguments
command_line_arguments_parser.add_argument(
    "--my_optional_string",
    type=str,
    help="This is a optional test string argument",
    default="hello world",
)
  • 示例代码
# Import the lib
import argparse
# Instantiate the parser
command_line_arguments_parser = argparse.ArgumentParser()
# Add optional arguments
command_line_arguments_parser.add_argument(
    "--my_optional_string",
    type=str,
    help="This is a optional test string argument",
    default="hello world",
)
# Parse the arguments
command_line_args = command_line_arguments_parser.parse_args()
# Print all arguments
print(command_line_args)
# String arguments usage
print(command_line_args.my_optional_string)
  • 测试
# Test 1
python my_test.py

# Test 2
python my_test.py --my_optional_string "This is my test string."
# Results 1
Namespace(my_optional_string='hello world')
hello world

# Results 2
Namespace(my_optional_string='This is my test string.')
This is my test string.

对于不需要具体参数值,而只有True和False的参数,通常使用以下方式赋值:

# Add bool arguments(no argument value needed)
command_line_arguments_parser.add_argument(
    "-v",
    "--verbose",
    action="store_true",
    help="When True, prints out more information",
)
# Bool arguments usage
if command_line_args.verbose:
    print("This is a verbose print when --verbose is True")

使用参数

参数解析后,可以读取整个参数表,也可以读取参数表中具体参数的值:

# Parse the arguments
command_line_args = command_line_arguments_parser.parse_args()

# Print all arguments
print(command_line_args)

# Int arguments usage
print(f"Squared value of {command_line_args.my_positional_int_arg} is {command_line_args.my_positional_int_arg**2}")

# String arguments usage
print(command_line_args.my_optional_string)

# Bool arguments usage
if command_line_args.verbose:
    print("This is a verbose print when --verbose is True")

文章来源:https://blog.csdn.net/m0_56661101/article/details/134895270
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。