[英]Why does this argparse code behave differently between Python 2 and 3?
The following code, using argparse's subparsers, fails on Python 3 but runs as expected in Python 2. After comparing the docs, I still can't tell why. 下面的代码,使用argparse的subparsers,在Python 3上失败,但在Python 2中按预期运行。在比较文档后,我仍然无法说明原因。
#!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
def action(args):
print(args)
if __name__ == '__main__':
std = ArgumentParser(add_help=False)
std.add_argument('standard')
ap = ArgumentParser()
sp = ap.add_subparsers()
cmd = sp.add_parser('subcommand', parents=[std], description='Do subcommand')
cmd.add_argument('arg')
cmd.set_defaults(do=action)
args = ap.parse_args()
args.do(args)
The output from Python 2.7.6 is: Python 2.7.6的输出是:
me@computer$ python test.py
usage: test.py [-h] {subcommand} ...
test.py: error: too few arguments
In Python 3.3.5, I get: 在Python 3.3.5中,我得到:
me@computer$ python3 test.py
Traceback (most recent call last):
File "test.py", line 21, in <module>
args.do(args)
AttributeError: 'Namespace' object has no attribute 'do'
the latest argparse
release changed how it tested for required arguments, and subparsers fell through the cracks. 最新的
argparse
版本改变了它测试所需参数的方式,而subparsers则陷入了困境。 They are no longer 'required'. 它们不再是“必需的”。 http://bugs.python.org/issue9253#msg186387
http://bugs.python.org/issue9253#msg186387
When you get test.py: error: too few arguments
, it's objecting that you did not give it a 'subcommand' argument. 当你得到
test.py: error: too few arguments
,它反对你没有给它一个'子命令'参数。 In 3.3.5 it makes it past that step, and returns args
. 在3.3.5中,它使它超过该步骤,并返回
args
。
With this change, 3.3.5 should behave the same as earlier versions: 通过此更改,3.3.5应该与早期版本的行为相同:
ap = ArgumentParser()
sp = ap.add_subparsers(dest='parser') # dest needed for error message
sp.required = True # force 'required' testing
Note - both dest
and required
need to be set. 注意 - 需要设置
dest
和required
。 dest
is needed to give this argument a name in the error message. dest
需要在错误消息中为此参数指定名称。
This error: 这个错误:
AttributeError: 'Namespace' object has no attribute 'do'
was produced because the cmd
subparser did not run, and did not put its arguments (default or not) into the namespace. 是因为
cmd
subparser没有运行,并且没有将其参数(默认或不是)放入命名空间。 You can see that effect by defining another subparser, and looking at the resulting args
. 您可以通过定义另一个subparser并查看生成的
args
来查看该效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.