Python 2.7.5 argparse.add_argument()和自定义格式化程序_类中的神秘失败

Python 2.7.5 argparse.add_argument()和自定义格式化程序_类中的神秘失败,python,argparse,Python,Argparse,我正在尝试编写一个HelpFormatter的子类,用于argparse。格式化程序很简单;将其集成为子类并非如此。我在stackoverflow.com/questions/3853722/上找到了一个非常有用的例子,在Anthon的回答中 在Mac OS X 10.9.4上使用Python 2.7.5。当我尝试将HelpFormatter子类化时,我不断得到: ./testBlankLineHelpFormatter.py -q ******* LOADING MY CLASS Instan

我正在尝试编写一个HelpFormatter的子类,用于argparse。格式化程序很简单;将其集成为子类并非如此。我在stackoverflow.com/questions/3853722/上找到了一个非常有用的例子,在Anthon的回答中

在Mac OS X 10.9.4上使用Python 2.7.5。当我尝试将HelpFormatter子类化时,我不断得到:

./testBlankLineHelpFormatter.py -q
******* LOADING MY CLASS
Instantiating argparse.ArgumentParser
Traceback (most recent call last):
  File "./testBlankLineHelpFormatter.py", line 15, in <module>
    formatter_class=BlankLineHelpFormatter
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1600, in __init__
    help=_('show this help message and exit'))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1293, in add_argument
    raise ValueError("length of metavar tuple does not match nargs")
ValueError: length of metavar tuple does not match nargs
*我用一个驱动程序运行它,我也把它裁剪成这样:

#!/usr/bin/python
#
from __future__ import print_function
import argparse
import BlankLineHelpFormatter

print("Instantiating argparse.ArgumentParser")

parser = argparse.ArgumentParser(
    description="""
This work is licensed under a Creative Commons
Attribution-Share Alike 3.0 Unported License. For further information on
this license, look it up.
    """,
    formatter_class=BlankLineHelpFormatter
)

print("Adding --quiet\n")
parser.add_argument(
    "--quiet", "-q",      action='store_true',
    help='Suppress most messages.')

print("Instantiated, now trying parse_args")
args = parser.parse_args()

print("Back.")

print("You might want to try '-h'...")

sys.exit(0)
我查看了argparse库源代码,这个问题对我来说甚至在上下文中都没有意义。这是一个阻止子类化HelpFormatter的错误,还是我在剩下的代码中遗漏了一些东西


非常感谢您的帮助

您将传递一个
BlankLineHelpFormatter
模块作为格式化程序,而不是
BlankLineHelpFormatter
类。错误消息来自:

\u get\u formatter()
尝试调用模块来创建格式化程序,然后将产生的
TypeError
错误解释为其他内容

修复应该是指定

formatter_class=BlankLineHelpFormatter.BlankLineHelpFormatter

如果您感兴趣,argparse的格式化程序现在可以在(CCLI Attribute Share Samelike许可证)上使用。再次感谢@user2357112早些时候的帮助

这些类用于ANSI终端的格式。没有经过高度抛光(例如,自动编号尚未完成),但您可能会发现它们很有用

“MarkupUserFormatter”支持大部分mediaWiki、MarkDown和POD语法(甚至混合):


“ParagraphHelpFormatter”只是像默认的argparse格式化程序一样包装文本,只是它尊重空行。Bug报告、修复、增强等。欢迎。

您的代码显示
导入BlankLineHelpFormatter
,然后显示
formatter\u class=BlankLineHelpFormatter
,这表明您在那里传递的是一个模块,而不是一个实际的格式化程序类。
解析器执行的操作相当于
添加参数('-h',…)
,并通过尝试格式化其
help
行来测试其参数。但是在进入
\u format\u args
之前,它在
\u get\u formatter
中遇到了一个问题。因此出现了令人困惑的错误消息。
        # raise an error if the metavar does not match the type
        if hasattr(self, "_get_formatter"):
            try:
                self._get_formatter()._format_args(action, None)
            except TypeError:
                raise ValueError("length of metavar tuple does not match nargs")
formatter_class=BlankLineHelpFormatter.BlankLineHelpFormatter
import MarkupHelpFormatter
MarkupHelpFormatter.InputOptions["mediawiki"] = True
parser = argparse.ArgumentParser(
    description="""...your text, with mediawiki markup...""",
    epilog='...',
    formatter_class=MarkupHelpFormatter.MarkupHelpFormatter
)