Python 命令行解析工具 Argparse介绍(二)
Python 命令行解析工具 Argparse介绍(一) ==>传送门<==
可选参数
到目前为止,我们已经使用了位置参数。让我们来看下如何使用可选参数。
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument("--verbosity", help="increase output verbosity")
- args = parser.parse_args()
- if args.verbosity:
- print "verbosity turned on"
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print "verbosity turned on"
接下来是输出:
- $ python prog.py --verbosity 1
- verbosity turned on
- $ python prog.py
- $ python prog.py --help
- usage: prog.py [-h] [--verbosity VERBOSITY]
- optional arguments:
- -h, --help show this help message and exit
- --verbosity VERBOSITY
- increase output verbosity
- $ python prog.py --verbosity
- usage: prog.py [-h] [--verbosity VERBOSITY]
- prog.py: error: argument --verbosity: expected one argument
$ python prog.py --verbosity 1
verbosity turned on
$ python prog.py
$ python prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]
optional arguments:
-h, --help show this help message and exit
--verbosity VERBOSITY
increase output verbosity
$ python prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument
结果分析:
- 当--verbosity被指定时程序会输出回显,当没被指定时没有显示。
- 显示的那个参数是可选的,即使没有它程序也会正常运行。注意,在默认情况下如果参数没有被使用,那么相关的变量例如本例中的args.verbosity将被指定一个None值。
- 帮助信息有一点不同。
- 当使用--verbosity参数的时候它必须被指定一个值,任何一个。
- 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"
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"
结果分析:
- 现在选项并不是需要一个值,我甚至改变了它的名字用来匹配这个说法。注意,我们指定了一个新的关键词action,并且给他赋值为"store_true"。它的意思是,如果选项被指定了则将True赋值给args.verbose,没有指定则赋值Flash。
- 当你指定一个值的时候它才被解释为True值。
- 注意帮助信息的不同。
短选项
如果你熟悉命令行用法,你会注意到我还没有触及短选项的主题。这很简单:
- 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"
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
$ 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
请注意,新的功能也会显示在帮助信息上。
结合位置参数与可选参数
我们的程序不断增加复杂性:
- 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
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
$ 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
- 我们输入了位置参数,所以程序会有反应
- 次序无关紧要
我们如何给程序多个值并去利用他们呢:
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument("square", type=int,
- help="display a square of a given number")
- parser.add_argument("-v", "--verbosity", type=int,
- 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
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
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
接下来是输出:
- $ python prog.py 4
- 16
- $ python prog.py 4 -v
- usage: prog.py [-h] [-v VERBOSITY] square
- prog.py: error: argument -v/--verbosity: expected one argument
- $ python prog.py 4 -v 1
- 4^2 == 16
- $ python prog.py 4 -v 2
- the square of 4 equals 16
- $ python prog.py 4 -v 3
- 16
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16
除了最后一行,上面的测试都非常完美,它暴露了我们程序的一个小bug。现在我们通过限定--verbosity的值来修改它:
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument("square", type=int,
- help="display a square of a given number")
- parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
- 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
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
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
接下来是输出:
- $ python prog.py 4 -v 3
- usage: prog.py [-h] [-v {0,1,2}] square
- prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
- $ python prog.py 4 -h
- usage: prog.py [-h] [-v {0,1,2}] square
- positional arguments:
- square display a square of a given number
- optional arguments:
- -h, --help show this help message and exit
- -v {0,1,2}, --verbosity {0,1,2}
- increase output verbosity
$ python prog.py 4 -v 3
usage: prog.py [-h] [-v {0,1,2}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
$ python prog.py 4 -h
usage: prog.py [-h] [-v {0,1,2}] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity
注意,这些变化也体现在错误信息和帮助信息上。
让我们来使用一种不同的方法来处理verbosity参数,这是很常见的方法。这也是CPython 用来处理自己冗长的的参数的办法(查看输出Python --help):
- 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
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
我们来介绍另一个action的参数,”count“,它用来计算一个特定的可选参数出现的次数:
- $ python prog.py 4
- 16
- $ python prog.py 4 -v
- 4^2 == 16
- $ python prog.py 4 -vv
- the square of 4 equals 16
- $ python prog.py 4 --verbosity --verbosity
- the square of 4 equals 16
- $ python prog.py 4 -v 1
- usage: prog.py [-h] [-v] square
- prog.py: error: unrecognized arguments: 1
- $ python 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
- $ python prog.py 4 -vvv
- 16
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python 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
$ python prog.py 4 -vvv
16
- 是的,在我们前面的脚本中出了一个标志参数(就像action="store_true"),并且给出了相应的解释。
- 他们的行为都和action="store_true"相似。
- 刚刚我们演示了一下”计数“功能,在这之前你可能看到过这种做法。
- 并且,就像action="store_true"功能一样,如果你没有指定”-v“一个参数值,那它被视为一个None值。
- 可以预料,如果指定长形式的参数,我们可以得到同样的输出。
- 遗憾的是,我们的帮助信息并不能识别脚本新的功能,但是我们可以进一步优化我们的脚本(例如:修改帮助参数的关键字)。
- 最后一行输出暴露了我们程序的一个bug。
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument("square", type=int,
- help="display a square of a given number")
- parser.add_argument("-v", "--verbosity", action="count",
- help="increase output verbosity")
- args = parser.parse_args()
- answer = args.square**2
- # bugfix: replace == with >=
- 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
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
# bugfix: replace == with >=
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
接下来是输出:
- $ python prog.py 4 -vvv
- the square of 4 equals 16
- $ python prog.py 4 -vvvv
- the square of 4 equals 16
- $ python prog.py 4
- Traceback (most recent call last):
- File "prog.py", line 11, in <module>
- if args.verbosity >= 2:
- TypeError: unorderable types: NoneType() >= int()
$ python prog.py 4 -vvv
the square of 4 equals 16
$ python prog.py 4 -vvvv
the square of 4 equals 16
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 11, in <module>
if args.verbosity >= 2:
TypeError: unorderable types: NoneType() >= int()
#译者注:在Python2.X中并不会出现这个错误,但在Python3.X下会报错,Python3相对于Python2修改了很多地方。
- 第一行的输出还是很好的,修复了之前的bug,使我们可以输入任意>=2的数。
- 第三行输出出了问题。
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument("square", type=int,
- help="display a square of a given number")
- parser.add_argument("-v", "--verbosity", action="count", default=0,
- 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
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
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
我们刚刚介绍了另一个关键字,default。我们将它设置为0使它可以与任何int类型的值比较。记住,如果一个可选参数没有被指定,那它将是默认值None,这样他就不能与int类型值比较。(因此上文才会出现 TypeError)
接下来的输出:
- $ python prog.py 4
- 16
$ python prog.py 4
16
到目前为止,虽然我们涉及的东西还很浅,但根据我们所学的知识你可以做很多你想做的东西了。
更高级的用法
我们可以强化我们的程序不止用来计算平方:
- 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 "{} to the power {} equals {}".format(args.x, args.y, answer)
- elif args.verbosity >= 1:
- print "{}^{} == {}".format(args.x, args.y, answer)
- else:
- print answer
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 "{} to the power {} equals {}".format(args.x, args.y, answer)
elif args.verbosity >= 1:
print "{}^{} == {}".format(args.x, args.y, answer)
else:
print answer
接下来是输出:
- $ python prog.py
- usage: prog.py [-h] [-v] x y
- prog.py: error: the following arguments are required: x, y
- $ python prog.py -h
- usage: prog.py [-h] [-v] x y
- positional arguments:
- x the base
- y the exponent
- optional arguments:
- -h, --help show this help message and exit
- -v, --verbosity
- $ python prog.py 4 2 -v
- 4^2 == 16
$ python prog.py
usage: prog.py [-h] [-v] x y
prog.py: error: the following arguments are required: x, y
$ python prog.py -h
usage: prog.py [-h] [-v] x y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-v, --verbosity
$ python prog.py 4 2 -v
4^2 == 16
可以看出到目前为止,我们使用--verbosity来控制文本输出,接下来的例子我们将使用它显示更多的文本:
- 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 "Running '{}'".format(__file__)
- if args.verbosity >= 1:
- print "{}^{} ==".format(args.x, args.y),
- print answer
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 "Running '{}'".format(__file__)
if args.verbosity >= 1:
print "{}^{} ==".format(args.x, args.y),
print answer
接下来是输出:
- $ 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
$ 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
冲突选项
到目前为止我们已经了解了argparse.ArgumentParser的两种实例方法,现在我们来介绍第三种,argparse.ArgumentParser()。它允许我们定义冲突的选项。现在我们修改一下程序,使它的功能更具有实用性:我们将介绍--quite选项,它与--verbosity相反:
- 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)
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)
现在我们的程序很简单,因为我们去掉一些演示的功能,它的输出如下:
- $ python prog.py 4 2
- 4^2 == 16
- $ python prog.py 4 2 -q
- 16
- $ python prog.py 4 2 -v
- 4 to the power 2 equals 16
- $ 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
- $ python 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
$ python prog.py 4 2
4^2 == 16
$ python prog.py 4 2 -q
16
$ python prog.py 4 2 -v
4 to the power 2 equals 16
$ 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
$ python 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
这很容易理解,我所增加的最后一个输出向你展示了这种操作的灵活性--------长短参数掺杂使用。
在我们结束之前,你可能想让你的用户知道程序主要的作用,万一他们不知道:
- import argparse
- parser = argparse.ArgumentParser(description="calculate X to the power of Y")
- 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)
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
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)
注意usage信息的不同,以及[-v | -q],我们只能使用-v或者-q,但不能同时使用:
- $ python prog.py --help
- usage: prog.py [-h] [-v | -q] x y
- calculate X to the power of Y
- positional arguments:
- x the base
- y the exponent
- optional arguments:
- -h, --help show this help message and exit
- -v, --verbose
- -q, --quiet
$ python prog.py --help
usage: prog.py [-h] [-v | -q] x y
calculate X to the power of Y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet
结论
比起我们展示的内容,argparse模块提供了更多的信息。它的文档非常详细和深入,并且包含很多例子。学习了本教程你应该很容易消化这些知识,而不至于感到不知所措。
译者注:水平有限,如有不当,还请指正。