python 命令行参数 argparse详解

简介: 这篇文章是关于Python命令行参数解析库`argparse`的详细解释和使用教程。文中提供了完整的代码模板,包括如何定义命令行参数、如何添加位置参数、可选参数和布尔参数,以及如何解析和使用这些参数。文章还包含了示例代码和测试用例,以展示如何在实际程序中应用`argparse`库。

完整模板

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

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")
目录
相关文章
|
10天前
|
缓存 Shell 开发工具
[oeasy]python064_命令行工作流的总结_vim_shell_python
本文总结了命令行工作流中的关键工具和操作,包括vim、shell和Python。主要内容如下: 1. **上次回顾**:完成了输入输出的代码编写,并再次练习了vim的使用。 2. **shell基础**:介绍了shell环境及其基本命令,如`pwd`、`cd`、`ll -l`等。 3. **Python游乐场**:通过`python3`命令进入Python交互环境,可以进行简单计算和函数调用,常用函数有`help`、`ord`、`chr`等。 4. **vim编辑器**:详细讲解了vim的三种模式(正常模式、插入模式、底行命令模式)及其切换方法,以及常用的底行命令如`:w`、`:q`、`
45 15
|
2月前
|
分布式计算 MaxCompute 对象存储
|
4月前
|
存储 C++ Python
[oeasy]python037_ print函数参数_sep分隔符_separator
本文介绍了Python中`print`函数的`sep`参数,即分隔符。通过回顾上文内容,解释了类型与`type`的概念,并强调了参数类型的重要性。文章详细探讨了`print`函数如何使用`sep`参数来分隔输出值,默认分隔符为空格(序号32)。还讨论了如何修改分隔符为其他字符,如冒号,并解释了为何反斜杠需要使用双反斜杠表示。最后,文章追溯了`sep`名称的由来,以及相关词汇的历史背景,如盎格鲁-萨克逊人的武器和语言。
142 0
|
4月前
|
存储 算法 API
Python学习五:函数、参数(必选、可选、可变)、变量、lambda表达式、内置函数总结、案例
这篇文章是关于Python函数、参数、变量、lambda表达式、内置函数的详细总结,包含了基础知识点和相关作业练习。
63 0
|
4月前
|
Windows Python
【10月更文挑战第2天】「Mac上学Python 2」入门篇2 - 开发环境命令行操作与文件管理
本篇将详细介绍Windows和Mac系统中的常用命令行操作与文件管理,帮助用户掌握如何通过终端或命令提示符进行文件管理和操作开发环境。内容涵盖路径切换、文件与文件夹的创建、删除、查看文件内容等基本操作,这些技能是后续Python开发的基础。
155 6
【10月更文挑战第2天】「Mac上学Python 2」入门篇2 - 开发环境命令行操作与文件管理
|
4月前
|
Java 程序员 C++
【Python】链式、嵌套调用、递归、函数栈帧、参数默认值和关键字参数
【Python】链式、嵌套调用、递归、函数栈帧、参数默认值和关键字参数
50 0
【Python】链式、嵌套调用、递归、函数栈帧、参数默认值和关键字参数
|
4月前
|
存储 人工智能 开发工具
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
只需要通过向AI助理提问的方式输入您的需求,即可瞬间获得核心流程代码及参数,缩短学习路径、提升开发效率。
1485 4
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
|
5月前
|
机器学习/深度学习 PyTorch TensorFlow
Python实现深度学习学习率指数衰减的方法与参数介绍
学习率指数衰减提供了一种高效的动态调整学习率的手段,帮助模型在不同训练阶段以不同的学习速度优化,有利于提升模型性能和训练效率。通过合理设置衰减策略中的参数,可以有效地控制学习率的衰减过程,实现更加精确的模型训练调优。
119 0
|
9月前
|
存储 Python
Python函数参数传递
Python函数参数传递
84 1
|
Python
python之函数的参数传递(引用传递和值传递),查看变量的内存地址的方法
python之函数的参数传递(引用传递和值传递),查看变量的内存地址的方法

热门文章

最新文章