带有所需子命令的 argparse [英] argparse with required subcommands

查看:26
本文介绍了带有所需子命令的 argparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 python 的 argparse,如何使子命令成为必需参数?我想这样做是因为如果未指定子命令,我希望 argparse 出错.我覆盖了错误方法来打印帮助.我有 3 个深度嵌套的子命令,所以这不是简单地在顶层处理零参数的问题.

With python's argparse, how do I make a subcommand a required argument? I want to do this because I want argparse to error out if a subcommand is not specified. I override the error method to print help instead. I have 3-deep nested subcommands, so it's not a matter of simply handling zero arguments at the top level.

在下面的例子中,如果这样调用,我得到:

In the following example, if this is called like so, I get:

$./simple.py
$

我希望它做的是让 argparse 抱怨未指定所需的子命令:

What I want it to do instead is for argparse to complain that the required subcommand was not specified:

import argparse

class MyArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        self.print_help(sys.stderr)
        self.exit(0, '%s: error: %s\n' % (self.prog, message))

def main():
    parser = MyArgumentParser(description='Simple example')
    subs = parser.add_subparsers()
    sub_one = subs.add_parser('one', help='does something')
    sub_two = subs.add_parser('two', help='does something else')

    parser.parse_args()

if __name__ == '__main__':
    main()

推荐答案

3.3 中所需参数的错误消息发生了变化,并且子命令被遗忘了.

There was a change in 3.3 in the error message for required arguments, and subcommands got lost in the dust.

http://bugs.python.org/issue9253#msg186387

我建议解决这个问题,在定义 subparsers 之后设置 required 属性.

There I suggest this work around, setting the required attribute after the subparsers is defined.

parser = ArgumentParser(prog='test')
subparsers = parser.add_subparsers()
subparsers.required = True
subparsers.dest = 'command'
subparser = subparsers.add_parser("foo", help="run foo")
parser.parse_args()

更新

一个相关的拉取请求:https://github.com/python/cpython/pull/3027

这篇关于带有所需子命令的 argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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