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

查看:26
本文介绍了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

这是我的问题:我如何设法在 shell 中编写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天全站免登陆