夜owl

困到睡不着
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python学习笔记-argparse

Posted on 2025-11-19 16:48  夜owl  阅读(0)  评论(0)    收藏  举报

1. 介绍

argparse是python的Command-line parsing library

这个模块是一个受optparse启发的命令行解析库,具备以下特点:

  • 处理可选和位置参数
  • 生成详细的使用信息
  • 支持将解析器分派到子解析器

argparse模块包含以下公共类,用于命令行参数解析:

- ArgumentParser -- The main entry point for command-line parsing. 

- ArgumentError -- The exception raised by ArgumentParser objects when
    there are errors with the parser's actions.

- FileType -- A factory for defining types of files to be created. 

- Action -- The base class for parser actions. 

- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,

1.1. 一般流程

1.1.1. argparse.ArgumentParser创建解析器

The argparse module’s support for command-line interfaces is built around an instance of argparse.ArgumentParser. It is a container for argument specifications and has options that apply to the parser as whole:

parser \= argparse.ArgumentParser(
                    prog\='ProgramName',
                    description\='What the program does',
                    epilog\='Text at the bottom of help')

1.1.2. ArgumentParser.add_argument()`添加参数

The ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:


parser.add\_argument('filename')           \# positional argument
parser.add\_argument('-c', '--count')      \# option that takes a value
parser.add\_argument('-v', '--verbose',
                    action\='store\_true')  \# on/off flag

1.1.3. ArgumentParser.parse_args()解析参数

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object:

args \= parser.parse\_args()
print(args.filename, args.count, args.verbose)

1.2. 官方教程

argparse — Parser for command-line options, arguments and subcommands — Python 3.13.5 documentation

argparse 教程 — Python 3.13.5 文档

Argparse Tutorial — Python 3.13.5 documentation

2. argparse模块基础

2.1. ArgumentParser objects

参数名称 解释 示例代码
prog 程序的名称(默认:os.path.basename(sys.argv[0]) parser = argparse.ArgumentParser(prog='MyProgram')
usage 描述程序用法的字符串(默认:根据添加到解析器的参数生成) parser = argparse.ArgumentParser(usage='%(prog)s [options]')
description 在参数帮助之前显示的文本(默认:无文本) parser = argparse.ArgumentParser(description='这是一个示例程序。')
epilog 在参数帮助之后显示的文本(默认:无文本) parser = argparse.ArgumentParser(epilog='感谢使用!')
parents 一个包含ArgumentParser对象的列表,这些对象的参数也应包含在内 parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--parent_arg')
parser = argparse.ArgumentParser(parents=[parent_parser])
formatter_class 用于自定义帮助输出格式的类 parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
prefix_chars 前缀字符的集合,用于标记可选参数(默认:'-' parser = argparse.ArgumentParser(prefix_chars='+/')
fromfile_prefix_chars 前缀字符的集合,用于标记从文件中读取额外参数的文件(默认:无) parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
argument_default 全局参数默认值 parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
conflict_handler 解决冲突可选参数的策略(通常不需要) parser = argparse.ArgumentParser(conflict_handler='resolve')
add_help 是否添加-h/--help选项(默认:True parser = argparse.ArgumentParser(add_help=False)
allow_abbrev 是否允许长选项被缩写(默认:True parser = argparse.ArgumentParser(allow_abbrev=False)
exit_on_error 是否在错误发生时退出并显示错误信息(默认:True parser = argparse.ArgumentParser(exit_on_error=False)

2.2. The add_argument() method

ArgumentParser.add_argument(name or flags..., *[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest][, deprecated])

Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

  • name or flags - Either a name or a list of option strings, e.g. 'foo' or '-f', '--foo'.

  • action - The basic type of action to be taken when this argument is encountered at the command line.

  • nargs - The number of command-line arguments that should be consumed.

  • const - A constant value required by some action and nargs selections.

  • default - The value produced if the argument is absent from the command line and if it is absent from the namespace object.

  • type - The type to which the command-line argument should be converted.

  • choices - A sequence of the allowable values for the argument.

  • required - Whether or not the command-line option may be omitted (optionals only).

  • help - A brief description of what the argument does.

  • metavar - A name for the argument in usage messages.

  • dest - The name of the attribute to be added to the object returned by parse_args().

  • deprecated - Whether or not use of the argument is deprecated.

2.2.1. Positional arguments

Positional arguments是必选参数,也就是命令行必须输入,通过 add_argument() 方法加入,不带-或者--的name or flags

命令行支持模糊输入,当输入没有匹配到任何参数时,--为Positional arguments的输入,可以看模糊输入例子

2.2.2. Optional arguments

Optional arguments是可选参数,通过 add_argument() 方法加入,带-或者--name or flags , 默认都有个-h/--help的可选参数

Optional arguments 可以不用,用了就需要指定值,除非使用action或者default等关键词自动去配值

2.2.3. help

-h/--help的可选参数是默认的,help是参数的一个属性,其值为字符串,可以格式化参数%(prog)s输入变量的值,类似这样赋值help="echo the string you use %(prog)s here"

2.2.4. type

命令行参数应当被转换成的类型,输入不符合则会提示类型错误

parser.add_argument("square", help="display a square of a given number",
                    type=int)

python prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'

2.2.5. action

指定参数在命令行中出现的动作,可以理解为代替配置参数的值

parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
可配置项 用法解释 示例
'store' 默认动作,存储参数的值。 parser.add_argument('--foo', action='store', type=int)
'store_const' 存储由const参数指定的值。 parser.add_argument('--foo', action='store_const', const=42)
'store_true' 存储True值,常用于标志选项。 parser.add_argument('--verbose', action='store_true')
'store_false' 存储False值,常用于标志选项。 parser.add_argument('--quiet', action='store_false')
'append' 存储一个列表,并将每个参数值追加到列表中。 parser.add_argument('--foo', action='append', type=int)
'append_const' 存储一个列表,并将const参数指定的值追加到列表中。 parser.add_argument('--foo', action='append_const', const=42)
'extend' 存储一个列表,并将多个参数值扩展到列表中。 parser.add_argument('--foo', action='extend', nargs='+', type=int)
'count' 计算某个选项出现的次数,通常用于增加详细程度(verbosity)。 parser.add_argument('--verbose', '-v', action='count', default=0)
'help' 显示帮助信息并退出。 parser.add_argument('-h', '--help', action='help', help='Show this help message and exit.')
'version' 显示版本信息并退出。 parser.add_argument('--version', action='version', version='%(prog)s 1.0')

2.2.6. choice

指定参数输入值的范围,比如指定0,1,2

parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")

2.2.7. default

指定参数没有输入时默认的值

parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")

2.2.8. nargs

nargs 用法解释 示例
N(整数) 消耗 N 个命令行参数,并将它们组合成一个列表。 parser.add_argument('--foo', nargs=2)
'?' 消耗 0 或 1 个命令行参数。如果有参数则存储为单个值,否则使用 defaultconst 的值。 parser.add_argument('--foo', nargs='?', const='c', default='d')
'*' 消耗所有剩余的命令行参数,并将它们组合成一个列表。 parser.add_argument('baz', nargs='*')
'+' 消耗一个或多个命令行参数,并将它们组合成一个列表。如果没有任何参数,则报错。 parser.add_argument('foo', nargs='+')
default(默认) 如果未指定 nargs,则根据动作决定。通常会消耗一个命令行参数,并存储为单个值。 parser.add_argument('--foo')

2.3. The parse_args() method

ArgumentParser.parse_args(args=None, namespace=None) 方法用于将命令行参数字符串转换为对象,并将这些对象作为属性赋值给命名空间(namespace)。最后,它返回已填充的命名空间对象。
具体功能:

1.args:这是一个字符串列表,表示需要解析的参数。如果未提供,默认会使用 sys.argv 中的参数(即命令行传入的参数)。
2.namespace:这是一个用于存储解析结果的对象。默认情况下,如果不提供,它会创建一个新的空的 Namespace 对象。

在之前调用 add_argument() 时,已经确定了需要创建哪些对象以及如何分配它们。

2.4. add_mutually_exclusive_group

add_mutually_exclusive_group方法可以生成一个组,组内添加的参数不能同时输入

group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")


python prog.py 4 2 -vq
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

2.5. 示例参考

2.5.1. 一般流程

从命令行中获取整数并将其求和结果写入文件:

parser = argparse.ArgumentParser(
    description='sum the integers at the command line')
parser.add_argument(
    'integers', metavar='int', nargs='+', type=int,
    help='an integer to be summed')
parser.add_argument(
    '--log', default=sys.stdout, type=argparse.FileType('w'),
    help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()

下面的是官方教程的例子

2.5.2. 多个参数进行运算

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print(f"{args.x} to the power {args.y} equals {answer}")
elif args.verbosity >= 1:
    print(f"{args.x}^{args.y} == {answer}")
else:
    print(answer)

2.5.3. 使用可选参数的复数等级控制log

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print(f"Running '{__file__}'")
if args.verbosity >= 1:
    print(f"{args.x}^{args.y} == ", end="")
print(answer)

Output:

$ python prog.py 4 2
16
$ python prog.py 4 2 \-v
4^2 == 16
$ python prog.py 4 2 \-vv
Running 'prog.py'
4^2 == 16

2.5.4. 模糊输入的区别

当输入没有匹配到任何参数时,--为Positional arguments的输入

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-n', nargs='+')
parser.add_argument('args', nargs='*')

# ambiguous, so parse_args assumes it's an option
parser.parse_args(['-f'])



parser.parse_args(['--', '-f'])


# ambiguous, so the -n option greedily accepts arguments
parser.parse_args(['-n', '1', '2', '3'])


parser.parse_args(['-n', '1', '--', '2', '3'])