我正在使用argparse,我想在我的選項的幫助文本中顯示一個列表。但是,argparse會從文本中刪除新行並將其顯示在單行上。Python argparse:預格式化幫助文本?
有無論如何告訴argparse幫助字符串是預先格式化的,而不是去掉換行符?
我正在使用argparse,我想在我的選項的幫助文本中顯示一個列表。但是,argparse會從文本中刪除新行並將其顯示在單行上。Python argparse:預格式化幫助文本?
有無論如何告訴argparse幫助字符串是預先格式化的,而不是去掉換行符?
如果你只是想重寫一個選項,則不能使用RawTextHelpFormatter
。取而代之的子類HelpFormatter
,並提供該應處理「原始」的選項特別介紹(我用"R|rest of help"
):
import argparse
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
# this is the RawTextHelpFormatter._split_lines
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)
並使用它:
from argparse import ArgumentParser
from textwrap import dedent
parser = ArgumentParser(description='test')
parser.add_argument('--list', help=dedent("""\
R|abc
def
ghi
"""))
parser.parse_args()
任何其他調用.add_argument()
其中幫助不以R|
開始將被正常包裝。
這是my improvements on argparse的一部分。完整的SmartFormatter還支持將缺省值添加到所有選項,以及實用程序描述的原始輸入。
dup:http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text? – 2010-12-07 10:06:06