37

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

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

$./simple.py
$

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

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()
4

4 回答 4

62

3.3 中对所需参数的错误消息进行了更改,并且子命令消失在尘埃中。

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

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

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

于 2013-08-16T23:58:58.527 回答
13

除了hpaulj 的回答:您还可以使用required关键字参数 with ArgumentParser.add_subparsers()since Python 3.7。您还需要dest作为参数传递。否则会报错:TypeError: sequence item 0: expected str instance, NoneType found.

示例文件example.py

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command', required=True)
foo_parser = subparsers.add_parser("foo", help="command foo")
args = parser.parse_args()

不带参数的调用输出:

$ python example.py
usage: example.py [-h] {foo} ...
example.py: error: the following arguments are required: command
于 2019-04-24T16:09:24.650 回答
0

怎么用required=True?更多信息在这里

于 2013-08-16T21:32:38.227 回答
0

您可以使用该dest参数,该参数记录在文档的最后一个示例中add_subparsers()

# required_subparser.py
import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser_name')
one = subparsers.add_parser('one')
two = subparsers.add_parser('two')

args = parser.parse_args()

使用 Python 2.7 运行:

$python required_subparser.py 
usage: required_subparser.py [-h] {one,two} ...
required_subparser.py: error: too few arguments
$python required_subparser.py one
$# no error
于 2013-08-16T21:37:13.773 回答