gpt4 book ai didi

python - 带有自定义 formatter_class 的 Python 2.7.5 argparse.add_argument() 中的神秘失败

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:30 25 4
gpt4 key购买 nike

我正在尝试编写 HelpFormatter 的子类以与 argparse 一起使用。格式化程序很简单;将它集成为一个子类不是。在 Anthon 的回答中,我在 stackoverflow.com/questions/3853722/找到了一个非常有用的示例。

在 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

* 请注意,错误发生在实例化我的子类时,当标准类尝试添加“--help”项目时——它永远不会进入我的任何 add_argument() 调用。我将我的子类缩减为这个,但它仍然失败:

class BlankLineHelpFormatter(argparse.HelpFormatter):
"""
A formatter for argparse that just respects blank lines (as in, doesn't
wrap across them).

See also: http://bugs.python.org/issue12806

"""

sys.stderr.write("******* LOADING MY CLASS\n")

def __init__(self, *args, **kw):
sys.stderr.write("******* IN MY INIT\n")
super(BlankLineHelpFormatter, self).__init__(*args, **kw)

* 我正在使用我也精简过的驱动程序来运行它:

#!/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 类。错误信息来自this part of the argparse source :

        # 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")

_get_formatter() 尝试调用该模块来创建格式化程序,然后将生成的 TypeError 错误解释为其他内容。

修复应该是指定

formatter_class=BlankLineHelpFormatter.BlankLineHelpFormatter

关于python - 带有自定义 formatter_class 的 Python 2.7.5 argparse.add_argument() 中的神秘失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com