Python 2.x可选子解析器-错​​误的参数太少 [英] Python 2.x optionnal subparsers - Error too few arguments

查看:42
本文介绍了Python 2.x可选子解析器-错​​误的参数太少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图用两个子解析器设置一个主解析器,以便当单独调用时,主解析器将显示帮助消息.

I have been trying to set up a main parser with two subs parser so that when called alone, the main parser would display a help message.

def help_message():
    print "help message"

import argparse
parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(dest='sp')

parser_a = subparsers.add_parser('a')
parser_a.required = False
#some options...
parser_b = subparsers.add_parser('b')
parser_b.required = False
#some options....

args = parser.parse_args([])

if args.sp is None:
    help_message()
elif args.sp == 'a':
    print "a"
elif args.sp == 'b':
    print "b"

此代码在Python 3上运行良好,我希望在Python 2.x上也能运行

This code works well on Python 3 and I would like it to work aswell on Python 2.x

运行'python myprogram.py'时出现此错误

I am getting this when running 'python myprogram.py'

myprogram.py: error: too few arguments

这是我的问题:如何在外壳中编写"python myprogram.py"并获取帮助消息而不是错误.

Here is my question : How can i manage to write 'python myprogram.py' in shell and get the help message instead of the error.

推荐答案

我认为您正在处理 http中讨论的错误. ://bugs.python.org/issue9253

您的subparsers是位置参数.除非nargs='?'(或*),否则始终需要这种参数.我认为这就是为什么您在2.7中收到错误消息的原因.

Your subparsers is a positional argument. That kind of argument is always required, unless nargs='?' (or *). I think that is why you are getting the error message in 2.7.

但是在最新的py 3发行版中,更改了测试所需参数的方法,并且使次解析器陷入了困境.现在它们是optional(不是必需的).有一个建议的补丁/软糖可以使argparse像以前一样运行(需要子解析器条目).我希望最终py3 argparse会还原为py2实践(可以选择接受required=False参数).

But in the latest py 3 release, the method of testing for required arguments was changed, and subparsers fell through the cracks. Now they are optional (not-required). There's a suggested patch/fudge to make argparse behave as it did before (require a subparser entry). I expect that eventually py3 argparse will revert to the py2 practice (with a possible option of accepting a required=False parameter).

因此,代替测试args.sp is None,您可能需要在调用parse_args之前测试sys.argv[1:]. Ipython这样做是为了产生自己的帮助消息.

So instead of testing args.sp is None, you may want to test sys.argv[1:] before calling parse_args. Ipython does this to produce it's own help message.

这篇关于Python 2.x可选子解析器-错​​误的参数太少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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