【发布时间】:2014-05-24 07:59:51
【问题描述】:
以下代码使用 argparse 的子解析器,在 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)
Python 2.7.6 的输出是:
me@computer$ python test.py
usage: test.py [-h] {subcommand} ...
test.py: error: too few arguments
在 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'
【问题讨论】:
-
请注意,如果您使用子解析器:
args = cmd.parse_args()它会起作用。 -
这段代码在 Python 2.7.4 上似乎给了我同样的错误。很可能您正在运行错误的文件版本或其他内容。它不应该工作。再仔细尝试一下。
-
当我在 Python 2.7.6 解释器中输入您的代码时,我在
args = ap.parse_args()行收到同样的错误。
标签: python python-3.x argparse python-2.x