声明:
- 翻译自Python官方文档
- 本文并不是逐字翻译的,力求简要直观
Argparse指南
Argparse是一个Python模块,用于设置命令行中的命令参数。
概念
Linux系统中有一个命令ls
,它可以产看路径下的文件/文件夹。现在,我们以这个成熟的linux命令为参考,了解Argparse的作用。
$ ls
cpython devguide prog.py pypy rm-unused-function.patch
$ ls pypy
ctypes_configure demo dotviewer include lib_pypy lib-python ...
$ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide
-rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py
drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy
-rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
...
通过上面的示例,可以看出:
ls
命令在没有参数的时候也能发挥作用,此时是在默认参数下,展示当前路径下的文件/文件夹。- 若想实现更多的功能,需要为
ls
命令添加一些参数。在上面的命令2中,添加参数pypy
可以展示~/pypy
下的文件/文件夹。添加的这个参数是一个位置参数。即,在该位置下的值对应于特定的形参。就像是Linux中的复制命令cp SRC DEST
,第一个参数永远是源文件,第二个参数永远是目标文件。 - 在第3个命令中,我们改变了
ls
的展示方式,显示了文件/文件夹的更多信息。这里的-l
就是一个可选参数。 - 最后一个命令展示了帮助(help)文档的片段。
基础——简易例程
写一个简单的py程序prog.py
,在该程序中,我们不设置任何参数,仅仅是调用一下argparse
模块:
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
运行:
$ python prog.py
$ python prog.py --help
usage: prog.py [-h]
optional arguments:
-h, --help show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
通过上面的示例,可以看出:
- 直接运行程序,没有输出任何结果。
- 命令2体现了
argparse
模块的作用:虽然我们什么都没做,但该模块提供了一个默认的help
信息。 - 在未设置参数的情况下,只有
--help
及其简写-h
可用,其他的参数都将引起Python解释器报错。
位置参数(positional arguments)
添加一个位置参数
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo')
args = parser.parse_args()
print(args.echo)
运行:
$ python prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python prog.py --help
usage: prog.py [-h] echo
positional arguments:
echo
optional arguments:
-h, --help show this help message and exit
$ python prog.py foo
foo
通过上面的示例,可以看出:
- 在py程序中,我们通过
add_argument()
函数设置参数。 - 运行该py程序时,如果不输入参数,程序报错。
parse_args()
函数返回从命令行接受到的参数值。argparse
模块可以自动帮我们做好help
部分的功能。
上面示例中,
parser.parse_args()
函数返回的是什么?
type(args)
输出:
< class 'argparse.Namespace'>
print(args)
输出:
Namespace(echo='foo')
当然,我们发现自动生成的help
选项下,对命令参数的解释不够。下面,我们为help
选项添加一些内容:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo', help="echo the string you use here")
print(args.echo)
运行:
$ python prog.py -h
usage: prog.py [-h] echo
positional arguments:
echo echo the string you use here
optional arguments:
-h, --help show this help message and exit
参数值的数据类型
从命令行接受到的参数值的数据类型默认为str。下面是改变默认数据类型的例子:
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)
可选参数
设置可选参数的例子:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print("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
increase output verbosity
$ python3 prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument
通过上面的示例,可以看出:
- 通过设置参数
--verbosity
,显示一些信息。 - 这里可选参数不同于位置参数的地方在于:即使命令后不加任何参数,也不会报错。命令后不加参数时:参数值为
None
。 help
信息变了。help
信息中包含三部分:usage
,positional arguments
,optional arguments
。- 一旦使用了参数
--verbosity
,必须为其指定参数值(可以是任意值)。
确实,对于可视化选项而言,它只有两种取值True/False,还要再显式地指定任意值太麻烦。于是修改上面示例,仅需要在add_argument()
函数中添加一个参数action="store_true"
:
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")
运行:
$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose]
optional arguments:
-h, --help show this help message and exit
--verbose increase output verbosity
通过上面的示例,可以看出:
action="store_true"
:当命令后有参数--verbose
时,接收值为True;否则接收值为False。- 此时命令选项后面不能再加任意值了。
help
信息也变了。原来是--verbosity VERBOSITY ...
表示需要参数选项和参数值;现在是--verbose ...
表示只需要参数选项。
简写选项
命令的参数选项还可以简写!即命令python prog.py -v
与命令python prog.py -verbose
是等效的。
此时修改程序为:
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")
运行:
$ python prog.py -v
verbosity turned on
$ python prog.py --help
usage: prog.py [-h] [-v]
optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
位置参数和可选参数(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)
运行:
$ python prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python prog.py 4
16
$ python prog.py 4 --verbose
the square of 4 equals 16
$ python prog.py --verbose 4
the square of 4 equals 16
通过上面的示例,可以发现:
- 与传统的函数中参数传递不同的是,参数的顺序可以打乱。
PS:官方文档在这里还有很多鸡肋的东西,不在多做介绍。
延伸
为命令添加整体功能描述信息:
parser = argparse.ArgumentParser(description="balabala")
运行:
$ python3 prog.py --help
usage: prog.py [-h]
balabala
optional arguments:
-h, --help show this help message and exit
parser.parse_known_args()
除了args = parser.parse_args()
用于返回解析后的参数值,还有parse_known_args()
函数,详见博客园。