当前位置: 代码网 > it编程>前端脚本>Python > python中argparse模块用法详解(小白入门)

python中argparse模块用法详解(小白入门)

2026年01月27日 Python 我要评论
argparse 详细讲解argparse 是 python 标准库中的一个模块,专门用来处理命令行参数。什么是命令行参数?命令行参数就是你在运行程序时,在程序名字后面加的一些额外信息。举例说明:#

argparse 详细讲解

argparse 是 python 标准库中的一个模块,专门用来处理命令行参数

什么是命令行参数?

命令行参数就是你在运行程序时,在程序名字后面加的一些额外信息。

举例说明:

# 没有参数
python main.py

# 有参数
python main.py --debug --batch_size 32 --lr 0.001

这里的 --debug--batch_size 32--lr 0.001 就是命令行参数。

一、 含义与简介

argparse 是 python 标准库(从 python 3.2 开始引入,替代了旧的 optparsegetopt)中的一个模块,用于解析命令行参数

简单来说,当你在终端或命令提示符中运行一个 python 脚本时,你可能会在脚本名后面输入一些额外的信息,例如:

python my_script.py --input data.txt --verbose --output results.json

argparse 的作用就是:

  • 解析这些跟在脚本名后面的参数(如 --input, data.txt 等)。
  • 验证这些参数是否符合预期(例如,检查文件是否存在,参数类型是否正确)。
  • 自动生成帮助和使用说明(当用户使用 -h--help 时)。
  • 将这些参数转换为 python 对象(如字符串、整数、列表等),方便你在代码中使用。

它的核心目标是让您的脚本拥有一个标准、专业、用户友好的命令行界面。

二、核心概念与使用规则

使用 argparse 通常遵循以下四个步骤:

  1. 创建一个解析器对象 - 这是所有功能的起点。
  2. 添加参数 - 告诉解析器你期望哪些参数。
  3. 解析参数 - 让解析器去分析用户输入的命令行。
  4. 使用参数 - 在代码中使用解析后的结果。

三、 语法规范与详细用法

让我们通过一个具体的例子来学习,并逐步扩展其功能。

步骤 1:导入模块并创建解析器

import argparse

# 创建 argumentparser 对象,description 参数用于描述程序的功能,会显示在帮助信息中。
parser = argparse.argumentparser(description='这是一个处理文件的示例程序。')
  • argumentparser 是主要的类
  • description 是程序的描述,会在帮助信息中显示

步骤 2:添加参数

这是最核心的一步。使用 add_argument() 方法来定义参数。

参数主要分为两大类:

  • 位置参数:必须提供的参数,其含义由它在命令行中的位置决定。
    • 例如:cp source_file dest_file 中的 source_filedest_file
  • 可选参数:以 --- 开头的参数,顺序可以颠倒。
    • 例如:ls -l -als --all --long

a) 添加位置参数(必须提供的参数)

使用 add_argument(),第一个参数就是参数的名字(不带 -)。

# 添加一个位置参数 ‘filename'
parser.add_argument('filename', help='要处理的输入文件') # help 参数用于生成帮助信息

b) 添加可选参数(以 - 或 – 开头)

使用 add_argument(),第一个参数是短选项(如 -f)或长选项(如 --file),或者两者都提供。

短参数 :

形式:单个短横线 - 后跟单个字母
示例 :v, -h, -f

长参数:

形式:双短横线 – 后跟完整单词

示例:–verbose, --help, --file

推荐使用:同时提供短参数和长参数

# 添加一个可选参数 ‘--output' (短选项 ‘-o‘)
parser.add_argument('-o', '--output', help='输出文件的路径')

# 添加一个布尔标志,action=‘store_true' 表示如果指定了这个参数,其值为 true,否则为 false。
parser.add_argument('-v', '--verbose', action='store_true', help='显示详细处理信息')

# 指定参数类型,比如整数
parser.add_argument('-n', '--number', type=int, help='一个数字参数', default=1) # default 指定默认值

# 限制参数的选择范围
parser.add_argument('--mode', choices=['fast', 'slow', 'debug'], default='fast', help='程序运行模式')

add_argument 常用参数详解:

  • name/flags: 参数的名字或标签列表(如 'filename'['-o', '--output'])。
  • action: 当参数在命令行中出现时,要采取的动作。
    • 'store': 默认动作,存储参数的值。
    • 'store_true' / 'store_false': 存储 truefalse
    • 'store_const': 存储一个被 const 参数指定的常量值。
    • 'append': 将同一个参数出现的多个值存储到一个列表中。
  • type: 参数应该被转换成的类型(如 int, float, str)。
  • default: 如果参数未提供,则使用此默认值。
  • choices: 一个容器,参数的值必须是其中的一个。
  • required: 对于可选参数,是否必须提供(true/false)。慎用,因为这违反了“可选”的初衷。
  • help: 参数的简要描述。

add_argument 方法的详细参数

常用参数:

参数名作用示例
name/flags参数名称'--lr'['-l', '--lr']
type参数类型int, float, str
default默认值default=32
help帮助信息help='学习率'
action动作类型'store_true', 'store_const'
choices可选值列表choices=[1, 2, 3]
required是否必须required=true

action 参数详解:

# store_true: 如果指定了该参数,就存储 true,否则存储 false
parser.add_argument('--debug', action='store_true')
# python script.py --debug  →  args.debug = true
# python script.py          →  args.debug = false

# store_const: 存储一个固定值
parser.add_argument('--mode', action='store_const', const='fast')
# python script.py --mode  →  args.mode = 'fast'

# store: 存储提供的值(默认动作)
parser.add_argument('--name', type=str)
# python script.py --name alice  →  args.name = 'alice'

# append: 将多个值收集到列表中
parser.add_argument('--add', action='append')
# python script.py --add a --add b  →  args.add = ['a', 'b']

步骤 3:解析参数

调用 parse_args() 方法。它会自动查看 sys.argv(即命令行输入),进行解析,并返回一个包含所有参数值的命名空间对象。

args = parser.parse_args()
# 现在,你可以通过 args.参数名 来访问每个参数的值

步骤 4:使用参数

现在,你可以在你的程序逻辑中使用这些解析好的参数了。

print(f"正在处理文件: {args.filename}")
if args.verbose:
    print("详细模式已开启。")
if args.output:
    print(f"结果将输出到: {args.output}")
print(f"运行模式为: {args.mode}")
print(f"数字参数是: {args.number}")

四、完整示例与演示

完整示例1

让我们把所有代码组合起来,文件名为 example.py

import argparse

# 1. 创建解析器
parser = argparse.argumentparser(description='一个强大的文件处理工具。')

# 2. 添加参数
parser.add_argument('filename', help='输入文件的名称')
parser.add_argument('-o', '--output', help='输出文件的路径')
parser.add_argument('-v', '--verbose', action='store_true', help='开启详细输出')
parser.add_argument('-n', '--number', type=int, default=1, help='处理的次数 (默认: 1)')
parser.add_argument('--mode', choices=['fast', 'slow', 'debug'], default='fast', help='选择运行模式')

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

# 4. 使用参数
print(f"输入文件: {args.filename}")

if args.verbose:
    print("状态: 详细模式已激活。")
    print(f"正在以 '{args.mode}' 模式运行。")
    print(f"将处理 {args.number} 次。")

if args.output:
    print(f"输出将保存至: {args.output}")

# ... 这里是你实际的程序逻辑,例如读写文件等 ...

在命令行中的运行演示:

  1. 获取帮助(这是 argparse 自动提供的强大功能):

    python example.py -h
    

    输出:

    usage: example.py [-h] [-o output] [-v] [-n number] [--mode {fast,slow,debug}] filename
    
    一个强大的文件处理工具。
    
    positional arguments:
      filename              输入文件的名称
    
    optional arguments:
      -h, --help           show this help message and exit
      -o output, --output output
                            输出文件的路径
      -v, --verbose        开启详细输出
      -n number, --number number
                            处理的次数 (默认: 1)
      --mode {fast,slow,debug}
                            选择运行模式 (默认: fast)
    
  2. 正常使用

    python example.py data.txt -o out.json -v -n 5 --mode slow
    

    输出:

    输入文件: data.txt
    状态: 详细模式已激活。
    正在以 'slow' 模式运行。
    将处理 5 次。
    输出将保存至: out.json
    
  3. 使用错误参数argparse 会自动报错):

    python example.py
    # 错误: error: the following arguments are required: filename
    
    python example.py data.txt --mode superfast
    # 错误: error: argument --mode: invalid choice: 'superfast' (choose from 'fast', 'slow', 'debug')
    

完整示例2

import argparse

def main():
    # 1. 创建解析器
    parser = argparse.argumentparser(
        description='一个简单的文件处理程序',
        epilog='示例: python script.py input.txt --verbose --output result.txt'
    )
    
    # 2. 添加位置参数(必须提供)
    parser.add_argument('input_file', help='要处理的输入文件')
    
    # 3. 添加可选参数
    parser.add_argument('--output', '-o', 
                       type=str, 
                       default='output.txt',
                       help='输出文件名(默认: output.txt)')
    
    parser.add_argument('--verbose', '-v',
                       action='store_true',
                       help='显示详细处理信息')
    
    parser.add_argument('--count', '-c',
                       type=int,
                       default=1,
                       choices=[1, 2, 3, 4, 5],
                       help='处理次数(1-5,默认: 1)')
    
    # 4. 解析参数
    args = parser.parse_args()
    
    # 5. 使用参数
    print(f"输入文件: {args.input_file}")
    print(f"输出文件: {args.output}")
    print(f"详细模式: {args.verbose}")
    print(f"处理次数: {args.count}")
    
    # 模拟处理逻辑
    if args.verbose:
        print("开始处理文件...")
        print(f"正在处理: {args.input_file}")
        print(f"将保存到: {args.output}")
        print(f"将处理 {args.count} 次")

if __name__ == '__main__':
    main()

运行示例:

# 查看帮助
python script.py -h
# 输出:
# usage: script.py [-h] [--output output] [--verbose] [--count count] input_file
# 
# 一个简单的文件处理程序
# 
# positional arguments:
#   input_file           要处理的输入文件
# 
# optional arguments:
#   -h, --help           show this help message and exit
#   --output output, -o output
#                        输出文件名(默认: output.txt)
#   --verbose, -v        显示详细处理信息
#   --count count, -c count
#                        处理次数(1-5,默认: 1)
# 
# 示例: python script.py input.txt --verbose --output result.txt

# 正常运行
python script.py data.txt --verbose --output result.txt --count 3
# 输出:
# 输入文件: data.txt
# 输出文件: result.txt
# 详细模式: true
# 处理次数: 3
# 开始处理文件...
# 正在处理: data.txt
# 将保存到: result.txt
# 将处理 3 次

五、常见问题解答

1. 为什么有些参数用--,有些不用?

  • -- 的是可选参数,可以不提供
  • 不用 -- 的是位置参数,必须提供

2.action='store_true'是什么意思?

意思是:“如果用户提供了这个参数,就把它设为 true;如果没提供,就设为 false”

3. 参数名中的-和_有什么区别?

在代码中使用时,--batch-size 会变成 args.batch_size(横线变下划线)

4. 如何让某个参数是必须的?

parser.add_argument('--required_arg', required=true, help='这个参数必须提供')

六、总结

  • argparse 是 python 中用于构建命令行接口的标准工具。
  • 使用流程:创建解析器 → 添加参数 → 解析参数 → 使用结果
  • 它能自动处理 -h/--help 帮助信息和错误提示,大大提升了脚本的易用性和健壮性。
  • 通过 add_argument() 方法的丰富选项,你可以定义各种复杂的参数规则。

对于绝大多数命令行程序来说,argparse 的功能已经完全足够。它是每个 python 开发者都应该掌握的基础库之一。

argparse 就像是一个智能的"问卷调查系统":

  1. 设计问卷 - 用 argumentparseradd_argument 定义问题
  2. 用户填写 - 用户在命令行输入参数
  3. 自动批改 - parse_args() 自动解析并检查答案
  4. 获取结果 - 通过 args.参数名 获取用户的选择

到此这篇关于python中argparse模块用法的文章就介绍到这了,更多相关python中argparse模块用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com