argparse与必需的子命令 [英] argparse with required subcommands
问题描述
使用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屋!