为什么此argparse代码在Python 2和3之间的行为不同?

问题描述

最新argparse版本改变了它测试所需参数的方式,而次级解析器也陷入了困境。它们不再是“必需的”。http://bugs.python.org/issue9253#msg186387

当您获得时test.py: error: too few arguments,就会反对您没有给它一个“子命令”参数。在3.3.5中,它经过了该步骤,然后返回args

进行此更改后,3.3.5的行为应与早期版本相同:

ap = ArgumentParser()
sp = ap.add_subparsers(dest='parser')  # dest needed for error message
sp.required = True   # force 'required' testing

注-既destrequired需要进行设置。 dest需要在错误消息中为此参数命名。

这个错误:

AttributeError: 'Namespace' object has no attribute 'do'

之所以生成该cmd文件,是因为该子解析器未运行,并且没有将其参数(默认值或未设置)放入名称空间。您可以通过定义另一个子解析器并查看结果来查看效果args

解决方法

以下使用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'

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...