为什么此argparse代码在Python 2和3之间的行为有所不同? [英] Why does this argparse code behave differently between Python 2 and 3?

查看:127
本文介绍了为什么此argparse代码在Python 2和3之间的行为有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下使用argparse的子解析器的代码在Python 3上失败,但在Python 2中按预期运行.比较了文档之后,我仍然不知道为什么.

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.

#!/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的输出是:

The output from Python 2.7.6 is:

me@computer$ python test.py 
usage: test.py [-h] {subcommand} ...
test.py: error: too few arguments

在Python 3.3.5中,我得到:

In Python 3.3.5, I get:

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'

推荐答案

最新的argparse版本更改了测试必需参数的方式,并且子解析器陷入了困境.它们不再是必需的". http://bugs.python.org/issue9253#msg186387

the latest argparse release changed how it tested for required arguments, and subparsers fell through the cracks. They are no longer 'required'. http://bugs.python.org/issue9253#msg186387

得到test.py: error: too few arguments时,表示您不给它一个子命令"参数是反对的.在3.3.5中,它经过了该步骤,并返回args.

When you get test.py: error: too few arguments, it's objecting that you did not give it a 'subcommand' argument. In 3.3.5 it makes it past that step, and returns args.

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

With this change, 3.3.5 should behave the same as earlier versions:

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

注意-destrequired都需要设置.需要dest以便在错误消息中为该参数指定名称.

Note - both dest and required need to be set. dest is needed to give this argument a name in the error message.

此错误:

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

产生

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

was produced because the cmd subparser did not run, and did not put its arguments (default or not) into the namespace. You can see that effect by defining another subparser, and looking at the resulting args.

这篇关于为什么此argparse代码在Python 2和3之间的行为有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆