python命令行解析工具-argparse模块-官方文档解读

本文介绍了Python的argparse模块,用于处理命令行参数。内容包括创建ArgumentParser对象,添加位置参数和选项参数,解析参数以及Namespace对象的使用。通过示例解释了如何使用argparse创建命令行工具,包括选项参数的store、store_true/false、append等动作。还讨论了参数缩写、报错处理和避免参数混淆的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0.举个例子

官方文档(Document)
源码(Source code)

argparse是python用来处理命令行参数的模块,本文主要简述python3下该模块的常见使用方法。先看一个官网简单的例子

  1. 新建.py文件test1.py,文件内容如下:

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print(args.accumulate(args.integers))
    
  2. 在命令行运行该文件并加上’-h’命令时,可以友好的输出上述代码自定义的所有帮助信息

    $ python3 test1.py -h
    usage: test.py [-h] [--sum] N [N ...]
    
    Process some integers.
    
    positional arguments:
      N           an integer for the accumulator
    
    optional arguments:
      -h, --help  show this help message and exit
      --sum       sum the integers (default: find the max)
    

    从帮助信息中可以解读到(位置参数与选项参数区别本节末会进行讲解):

    • 代码描述(description):处理多个整数
    • 位置参数(positional arguments):用于累加的整数
    • 选项参数(optional arguments):
      • -h 显示帮助信息并退出
      • –sum 对整数进行求和,(如果没有,则默认输入最大值)
  3. 下面进行简单的测试

    $ python3 test.py 3 5 6 4
    6
    
    $ python3 test.py 3 5 6 4 --sum
    18
    

    正如帮助信息中所述,在命令行后面只添加整数时,返回最大值;加入–sum时,返回所有整数的和

  4. 输入不按要求来呢?

    $ python3 test.py
    usage: test.py [-h] [--sum] N [N ...]
    test.py: error: the following arguments are required: N
    
    $ python3 test.py a b c d
    usage: test.py [-h] [--sum] N [N ...]
    test.py: error: argument N: invalid int value: 'a'
    
    $ python3 test.py --sum
    usage: test.py [-h] [--sum] N [N ...]
    test.py: error: the following arguments are required: N
    

    argparse可以输出部分提示信息,应对很优雅。

  5. 注: 位置参数和选项参数的小tips(Tips about the difference between positional arguments and optional arguments)
    在命令行中,命令行参数分为位置参数和选项参数。

    • “ls /Users/pro” ls命令后面的指定路径就是位置参数

      $ ls /Users/pro
      Applications Documents    Library      Music        Pictures
      Desktop      Downloads    Movies       Public
      
    • “ls -l -h” ls命令后面-l与-h就是选项参数(加横杠表示选项参数开关)

      $ ls -l -h
      drwxrwxrwx   6 pro  staff   192B  2 22 10:47 data1
      drwxr-xr-x   5 pro  staff   160B  2 22 09:50 data2
      drwxr-xr-x@ 10 pro  staff   320B  3 11 09:11 data3
      
    • 为什么选项参数有的加一个横杠,又有的是两个横杠的情况,如“-h”与“–help”

      • 命令行为了简化输入,选项参数可以合并,即"ls -l -h"命令与“ls -lh”是相等的。换句话说,大于一个字母的选项参数会被分别解析。“ls -help"会被解析成"ls -h -e -l -p”
      • 为了避免上述情况发生,多于一个字母的选项参数,使用两个横杠。

下面对argparse模块进行详细阐述

1.第一步:导包并创建对象

  1. 使用argparse的第一步就是导入该包,并且创建一个ArgumentParser对象

    import argparse
    parser = argparse.ArgumentParser()
    

    创建对象时,ArgumentParser该方法的参数一般只使用"description=",即

    import argparse
    parser = argparse.ArgumentParser(description='这个程序是做什么的')
    
  2. 所有参数

    parser = argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
    
    参数 原文解释 中文释义
    prog The name of the program (default: sys.argv[0]) 程序名
    usage The string describing the program usage (default: generated from arguments added to parser) 程序使用说明(默认生成添加到对象的参数)
    description Text to display before the argument help (default: none) 程序描述(默认:空),一般只需要填写该选项
    epilog Text to display after the argument help (default: none) 后记(默认:空)
    parents A list of ArgumentParser objects whose arguments should also be included ArgumentParser对象的父对象的参数列表
    formatter_class A class for customizing the help output help说明格式
    prefix_chars The set of characters that prefix optional arguments (default: ‘-‘) 命令行参数的前缀(默认"-")
    fromfile_prefix_chars The set of characters that prefix files from which additional arguments should be read (default: None) 该读取其他参数的前缀文件的字符集(默认空)
    argument_default The global default value for arguments (default: None) 全局参数默认值(默认空)
    conflict_handler The strategy for resolving conflicting optionals (usually unnecessary) 解决冲突的策略(通常是不必要的)
    add_help Add a -h/–help option to the parser (default: True) 是否增加help选项(默认:是)
    allow_abbrev Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True) 是否使用参数的缩写(默认:是)

2.第二步:添加自己所需命令行参数

  1. 向已创建的对象中添加自己所需的命令行参数

    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值