如何打印Argparse主解析器的帮助(使用)部分而不是子解析器的使用?

鲍勃·麦克布森

我已经用Argparse编写了命令行程序已有一段时间了,我试图以这样的方式编写它:当用户向命令行提供以下内容时:

$python my_script.py -h

将打印出一个帮助部分(用法),该部分将打印出主解析器的帮助部分,以及子解析器的简要概述。

但是现在,每当我在终端中输入上一行时,我都不会使用它,而是会得到大量的回溯和以下错误:

TypeError: expected string or buffer

我以前从未使用基于argparse的命令行程序发生此错误。此外,如果我提供了一个次级解析器的名称,

$python my_script.py subparserA -h

我得到了子解析器用法的打印输出。其他次级解析器也是如此。

那么,为什么我无法获得主解析器的用法?这以前对我有用,所以我不知道为什么现在不起作用。我真的希望用户能够查看可用的不同子解析器的概述。

目前,我的基本代码是通过以下方式设置的:

import argparse
import sys

if __name__ == "__main__":
    Parser = argparse.ArgumentParser(prog= "My_program")

    Parser.description= "This program does A and B things."
    subparsers= Parser.add_subparsers(help= "SubparserA does A things and SubparserB does B things", dest='mode')

    subparserA= subparsers.add_parser("subparserA", help= "Additional explanation of what A things entail")

    subparserA.add_arguments("-foo", required=True, help= "foo is needed for SubparserA to work")

    subparserB= subparsers.add_parser("subparserB", help="Additional explanation of what B things entail")

    subparserB.add_argument("-bar", required=True, help= "bar is needed for SubparserB to work")

    args= Parser.parse_args()

    if args.mode == "subparserA":
        ###do things pertinent to subparserA
    elif args.mode== "subparserB":
        ###do things pertinent to subparserB
    else:
        argparse.print_help()
        argparse.ArgumentError("too few arguments")

更新

这是错误的完整回溯:

Traceback (most recent call last):
  File "my_program.py", line 164, in <module>
    args= Parser.parse_args()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1701, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1733, in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1939, in _parse_known_args
    start_index = consume_optional(start_index)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1879, in consume_optional
    take_action(action, args, option_string)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1807, in take_action
    action(self, namespace, argument_values, option_string)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 996, in __call__
    parser.print_help()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2340, in print_help
    self._print_message(self.format_help(), file)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2314, in format_help
    return formatter.format_help()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 281, in format_help
    help = self._root_section.format_help()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 211, in format_help
    func(*args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 485, in _format_text
    return self._fill_text(text, text_width, indent) + '\n\n'
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 621, in _fill_text
    text = self._whitespace_matcher.sub(' ', text).strip()
TypeError: expected string or buffer
hpaulj

您应该使用

Parser.print_help()
Parser.error('too few arguments')

那就是现有Parser对象的使用方法


当我运行您的脚本时

1019:~/mypy$ python stack46754855.py 
Traceback (most recent call last):
  File "stack46754855.py", line 10, in <module>
    subparserA= subparsers.add_parser("subparserA", help= "Additional explanation of what A things entail", dest= 'mode')
  File "/usr/lib/python2.7/argparse.py", line 1066, in add_parser
    parser = self._parser_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'dest'

dest是该add_parser方法的无效参数它是的有效且有用的参数add_subparsers

subparsers= Parser.add_subparsers(dest='mode')

它还反对该add_arguments方法。

更正后,我得到:

1022:~/mypy$ python stack46754855.py 
usage: My_program [-h] {subparserA,subparserB} ...
My_program: error: too few arguments

在Py2中,subparsers是必填参数。在Py3中它是可选的(一个错误),允许脚本运行到无效的argparse.print_help调用:

1022:~/mypy$ python3 stack46754855.py 
Traceback (most recent call last):
  File "stack46754855.py", line 27, in <module>
    argparse.print_help()
AttributeError: module 'argparse' has no attribute 'print_help'

通过上面我建议的更改:

1025:~/mypy$ python3 stack46754855.py 
usage: My_program [-h] {subparserA,subparserB} ...

This program does A and B things.

positional arguments:
  {subparserA,subparserB}
                        SubparserA does A things and SubparserB does B things
    subparserA          Additional explanation of what A things entail
    subparserB          Additional explanation of what B things entail

optional arguments:
  -h, --help            show this help message and exit
usage: My_program [-h] {subparserA,subparserB} ...
My_program: error: too few arguments

第二个usage来自Parser.error通话。


我无法复制你的

大量回溯和以下错误:TypeError:预期的字符串或缓冲区

我需要查看该追溯(或其中的一部分),以了解到底是什么引起了错误。那不是正常的argparse错误;当然,不是argparse陷阱和重新路由。


有关如何使用带有Python 2.7的Argparse模块设置默认子解析器的更多关于必需/非必需子解析器行为的信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章