Why does this argparse code behave differently between Python 2 and 3?

跟風遠走 提交于 2019-11-28 10:01:12
hpaulj

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

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.

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

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


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. You can see that effect by defining another subparser, and looking at the resulting args.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!