Python 杂记:argparse 模块

简介

Python 标准库中提供了 argparse 模块用于解析命令行参数。

使用它的简单三个步骤:

  • 创建 argparse.ArgumentParser() 对象
  • 调用 add_argument() 方法添加参数配置
  • 调用 parse_args() 方法解析参数

然后,我们就可以通过 parse_args() 方法返回的对象来访问用户传入的命令行参数了。

示例一

示例代码如下:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--src", help="Source file", required=True)
parser.add_argument("-d", "--dst", help="Destination directory")      # 可选参数
parser.add_argument("--level", help="Running level", type=int, default=2)
parser.add_argument("--debug", help="Running in debug mode", action="store_true") # 不用指定参数值,默认为 True
args = parser.parse_args()
print(args) # 这里还可以通过 args.src、args.dst、args.level、args.debug 直接访问各个参数值

# 测试示例:
1> python test.py --src test.txt
Namespace(debug=False, dst=None, level=2, src='test.txt')

2> python test.py --src test.txt --dst test.out --debug
Namespace(debug=True, dst='test.out', level=2, src='test.txt')

3> python test.py --help         # 默认是会添加 -h, --help 参数的,并且可以直接打印 usage 信息
usage: test.py [-h] -s SRC [-d DST] [--level LEVEL] [--debug]

optional arguments:
  -h, --help         show this help message and exit
  -s SRC, --src SRC  Source file
  -d DST, --dst DST  Destination directory
  --level LEVEL      Running level
  --debug            Running in debug mode

其中:

  • 以“-”开头指定可用的命令行参数:

    • 以一个横线“-”开头的选项称为“短选项”
    • 以两个横线“-”开头的称为“长选项”
    • parse_args() 返回对象的属性中,默认使用第一个长选项名字保存该参数值
    • 若没有指定长选项,则默认使用第一个端选项名字保存
    • 若参数名字中也包含横线(例如:--ignore-error),则其中横线替换为下划线(属性名为 ignore_error )
  • help 用于设置指定显示在 help 文档中的描述

  • required 用于指定该参数是否为必需参数,默认为可选参数

  • type 用于指定该参数值的类型(会自动做类型检查和转换)

  • default 用于指定在省略该参数时的默认值

  • action="store_true" 用于表明该参数可以不带参数值,默认值为 True,若是使用“store_false”,则默认为 False

示例二

像 mv 这类 linux 命令,我们可以只传入参数值,而不需要指定参数名,例如:

mv file1 file2

要实现这种参数,add_argument() 中的参数可以指定名字(而不是以横线开头的选项),例如:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", help="A required option", required=True)
parser.add_argument("src", help="Source file")
parser.add_argument("dst", help="Destination file or directory")
parser.add_argument("--force", help="Force to rename or remove", action="store_true")
args = parser.parse_args()
print(args)     # 我们也可以直接使用 args.src 和 args.dst 直接访问这俩参数

# 测试示例:
1> python test.py file1 file2
Namespace(dst='file2', src='file1')

2> python test.py --force file1 --foo 123 file2
Namespace(dst='file2', foo='123', force=True, src='file1')

这种参数也叫“位置参数”,所有位置参数出现的顺序需与 add_argument() 的调用顺序相同,不过对于“非位置参数”(以横线开头的选项参数)不受此限制。

其它说明

add_argument() 方法中有两个有用的参数:

  • dest:前面示例一的描述中提到 parse_args() 返回对象的属性名的默认规则,若用户在调用 add_argument() 指定了 dest 参数,也可以强制自定义属性名。
  • metavar:用于指定该参数在 help 信息中显示的名字

关于该模块更多描述,请参考:https://docs.python.org/3/library/argparse.html

原文地址:https://www.cnblogs.com/itwhite/p/12433360.html