argparse之活学活用

本文详细介绍Python标准库中的argparse模块,包括位置参数和可选参数的定义与使用、短选项及互斥选项组的配置方法,并通过实际案例展示如何解析命令行参数。

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

argparse之活学活用

标签(空格分隔): Python


tutorials:

argparse.html
Argparse Tutorial


Argparse Turorial

argparse是一个非常好用的输入参数解析模块,与其功能相似的还有getopt和optparse。如果你厌倦了用sys.argv[0],sys.argv[1]…获取输入参数,argparse是一个非常简单且智能的替代方案。

The basics

argparse的起手式非常简单:
prog.py

# 这段代码仅仅初始化了一个ArgumentParser对象,什么也没做。
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

running the code:

$ python3 prog.py

$ python3 prog.py --help
usage: prog.py [-h]

optional arguments:
  -h, --help  show this help message and exit

$ python3 prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose

$ python3 prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo

以上运行结果说明:

  • -h或–help:optional arguments(可选参数),而且不需要添加(add_argument)就可以使用的,用于显示帮助信息。
  • –verbose,由于没有添加,所以无法识别。
  • foo:positional arguments,该参数跟出现的位置有关,同样没有添加也无法识别

接下来分别介绍Positional arguments和Optional arguments。

Introducing Positional arguments

A example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)

And running the code:

$ python3 prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo

$ python3 prog.py --help
usage: prog.py [-h] echo

positional arguments:
  echo          echo the string you use here

optional arguments:
  -h, --help  show this help message and exit

$ python3 prog.py "Hello,World!"
Hello,World!

这个例子说明:

  • 如果添加了positional arguments,则在调用prog.py时必须指定positional arguments。
  • 指定的”Hello,World!”赋值给了echo对象。
  • 可以通过help=”displayed messages”来指定帮助信息

Another example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print(args.square**2)

Following is a result of running the code:

$ python3 prog.py 4
16

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

这个例子说明:

  • 可以通过type来指定输入参数的类型

Introducing Optional arguments

举个例子:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", "-v", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")

And the output:

$ python3 main.py -v 1
verbosity turned on

$ python3 prog.py --verbosity 1
verbosity turned on

$ python3 prog.py

$ python3 prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY, -v VERBOSITY
                        increase output verbosity

$ python3 prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument

这个例子说明:

  • –verbosity或-v是可选参数,可以指定或者不指定,但一旦指定则后面必须要跟一个值。

action=”store_true”

example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

And the output:

$ python3 prog.py --verbose
verbosity turned on

$ python3 prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1

$ python3 prog.py --help
usage: prog.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

the value “store_true”. This means that, if the option is specified, assign the value True to args.verbose. Not specifying it implies False.

也就是说,如果有–verbose,则该值为True;如果没有,则该值为False

action=”count”

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

We have introduced another action, “count”, to count the number of occurrences of a specific optional arguments:

$ python3 prog.py 4
16

$ python3 prog.py 4 -v
4^2 == 16

$ python3 prog.py 4 -vv
the square of 4 equals 16

$ python3 prog.py 4 --verbosity --verbosity
the square of 4 equals 16

$ python3 prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1

$ python3 prog.py 4 -h
usage: prog.py [-h] [-v] square

positional arguments:
  square           display a square of a given number

optional arguments:
  -h, --help       show this help message and exit
  -v, --verbosity  increase output verbosity

$ python3 prog.py 4 -vvv
16

action=”count”,可以对该参数进行计数(例如:-vv,-v -v等),可选参数后面不需接具体值。


Short options

通常,我们发现输入参数会有完整参数和简写参数两种形式,分别用’–’和’-‘作前缀,如下面这个例子中的”–verbose”和”-v”。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

And here goes:

$ python3 prog.py -v
verbosity turned on

$ python3 prog.py --help
usage: prog.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

Combining Positional and Optional arguments

下面,我们尝试将位置参数和可选参数一起混合使用。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print("the square of {} equals {}".format(args.square, answer))
else:
    print(answer)

And now the output:

$ python3 prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square

$ python3 prog.py 4
16

$ python3 prog.py 4 --verbose
the square of 4 equals 16

$ python3 prog.py --verbose 4
the square of 4 equals 16
  • 如果添加了位置参数,则必须指定位置参数。
  • 位置参数和可选参数的顺序可以交换

Conflicting options

parser.add_mutually_exclusive_group(): optional arguments互斥,不能同时使用。

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
    print("{}^{} == {}".format(args.x, args.y, answer))

here’s the output:

$ python3 prog.py 4 2
4^2 == 16
$ python3 prog.py 4 2 -q
16
$ python3 prog.py 4 2 -v
4 to the power 2 equals 16
$ python3 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
$ python3 prog.py 4 2 -v --quiet
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
  • [-v | -q]表明我们可以指定-v或者-q,但不能两个同时指定。

Conclusion

以上几个小节的内容,介绍argparse模块的基本用法,通过附带的实例,差不多可以应对日常使用的需要。
总结起来,主要有三个步骤:
1. 实例化:argparse.ArgumentParser
2. 添加位置参数或可选参数:add_argument
3. 提取参数:parse_args
对argparse的进一步探索,继续看下一篇。

`argparse` 是 Python 标准库中用于解析命令行参数和选项的模块。它可以让你的 Python 脚本更加灵活,可以从命令行中接收参数和选项,并且可以根据用户提供的参数来执行不同的操作。下面是一些使用 `argparse` 的笔记: ### 基本示例 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') parser.add_argument('--url', type=str, help='需要处理的URL') parser.add_argument('--file', type=str, help='需要处理的文件路径') args = parser.parse_args() if args.url: print('处理URL:', args.url) elif args.file: print('处理文件:', args.file) else: print('请提供URL或文件路径') ``` 在上面的例子中,我们使用 `argparse` 创建了一个解析器对象,然后添加了两个参数 `--url` 和 `--file`。`type` 参数指定了参数的类型,`help` 参数指定了参数的帮助信息。最后,使用 `parse_args()` 方法解析命令行参数,并根据参数执行不同的操作。 ### 必需参数 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') parser.add_argument('input', type=str, help='输入文件路径') parser.add_argument('output', type=str, help='输出文件路径') args = parser.parse_args() print('输入文件:', args.input) print('输出文件:', args.output) ``` 在上面的例子中,我们将参数 `input` 和 `output` 指定为必需参数,这意味着用户必须在命令行中提供这两个参数,否则程序将会抛出异常。 ### 默认值 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') parser.add_argument('--url', type=str, help='需要处理的URL', default='https://www.baidu.com') parser.add_argument('--file', type=str, help='需要处理的文件路径', default='data.txt') args = parser.parse_args() print('处理URL:', args.url) print('处理文件:', args.file) ``` 在上面的例子中,我们为参数 `--url` 和 `--file` 指定了默认值,这意味着如果用户没有在命令行中提供这两个参数,那么程序将使用默认值。默认值可以是任何类型的值,不仅仅限于字符串类型。 ### 多个值 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') parser.add_argument('--input', type=str, help='输入文件路径', nargs='+') parser.add_argument('--output', type=str, help='输出文件路径') args = parser.parse_args() print('输入文件:', args.input) print('输出文件:', args.output) ``` 在上面的例子中,我们将参数 `--input` 指定为多个值,这意味着用户可以在命令行中提供多个输入文件路径,例如 `--input file1.txt file2.txt`。使用 `nargs='+'` 将参数指定为多个值,使用 `args.input` 来访问这些值。 ### 限制值的范围 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') parser.add_argument('--size', type=int, help='图像大小', choices=[256, 512, 1024]) args = parser.parse_args() print('图像大小:', args.size) ``` 在上面的例子中,我们将参数 `--size` 指定为整数类型,并且限制了它的取值范围只能是 256、512 或 1024。如果用户在命令行中指定了一个不在这个范围内的值,程序将会抛出异常。 ### 子命令 ```python import argparse parser = argparse.ArgumentParser(description='命令行参数解析示例') subparsers = parser.add_subparsers(title='子命令', description='可用的子命令') parser_a = subparsers.add_parser('a', help='子命令A') parser_a.add_argument('--input', type=str, help='输入文件路径') parser_a.add_argument('--output', type=str, help='输出文件路径') parser_b = subparsers.add_parser('b', help='子命令B') parser_b.add_argument('--url', type=str, help='需要处理的URL') args = parser.parse_args() if hasattr(args, 'input'): print('处理文件:', args.input) print('输出文件:', args.output) elif hasattr(args, 'url'): print('处理URL:', args.url) else: print('请提供子命令参数') ``` 在上面的例子中,我们使用 `add_subparsers()` 方法创建了子命令解析器对象,并添加了两个子命令 `a` 和 `b`。然后,我们为每个子命令添加了不同的参数。最后,根据子命令参数执行不同的操作。 以上就是一些 `argparse` 的基本使用笔记,希望对你有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值