我曾经遇到过类似的问题(Python 2.7.6)。我试图使用 RawTextHelpFormatter
将描述部分拆分成几行:
parser = ArgumentParser(description="""First paragraph
Second paragraph
Third paragraph""",
usage='%(prog)s [OPTIONS]',
formatter_class=RawTextHelpFormatter)
options = parser.parse_args()
所以RawTextHelpFormatter
不是一个解决方案。因为它按照源代码中出现的样式打印描述,保留所有空格字符(我希望在我的源代码中保留额外的制表符以提高可读性,但我不想打印它们全部。另外,原始格式化程序在行过长(例如超过80个字符)时不换行)。
感谢@Anton,他启发了正确的方向上面。但该解决方案需要稍作修改才能格式化description部分。
无论如何,需要自定义格式化程序。我扩展了现有的HelpFormatter
类,并重写了_fill_text
方法,如下所示:
import textwrap as _textwrap
class MultilineFormatter(argparse.HelpFormatter):
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
paragraphs = text.split('|n ')
multiline_text = ''
for paragraph in paragraphs:
formatted_paragraph = _textwrap.fill(paragraph, width, initial_indent=indent, subsequent_indent=indent) + '\n\n'
multiline_text = multiline_text + formatted_paragraph
return multiline_text
与来自 argparse 模块的原始源代码进行比较:
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent)
在原始代码中,整个描述被包装在一起。而在上面的自定义格式化程序中,整个文本被分成几个块,并且每个块都独立地进行格式化。
因此,在使用自定义格式化程序时:
parser = ArgumentParser(description= """First paragraph
|n
Second paragraph
|n
Third paragraph""",
usage='%(prog)s [OPTIONS]',
formatter_class=MultilineFormatter)
options = parser.parse_args()
输出结果为:
使用方法:play-with-argparse.py [选项]
第一段
第二段
第三段
可选参数:
-h, --help 显示帮助信息并退出
argparse
完成的,而不是解释器完成的,所以改用"""..."""
也没有帮助。 - kennytm