我遇到過類似的問題(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()
,並得到:
usage: play-with-argparse.py [OPTIONS]
First paragraph
Second paragraph
Third paragraph
optional arguments:
-h, --help show this help message and exit
所以RawTextHelpFormatter
是不是一個解決方案。因爲它打印出現在源代碼中的描述,保留所有空白字符(爲了便於閱讀,我想在源代碼中保留額外的標籤,但我不想將它們全部打印出來。太長,例如超過80個字符)。
非常感謝@Anton啓發了正確的方向above。但是該解決方案需要稍作修改才能格式化說明部分。
無論如何,自定義格式化程序是必要的。我擴展現有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()
輸出爲:
usage: play-with-argparse.py [OPTIONS]
First paragraph
Second paragraph
Third paragraph
optional arguments:
-h, --help show this help message and exit
我沒有Python 2.7,所以我可以測試我的想法。如何在三重引號中使用幫助文本(「」「」「」)。新的生產線是否能夠繼續生存下去? – pyfunc 2010-10-04 08:48:01
@pyfunc:不可以。剝離是由'argparse'在運行時完成的,而不是解釋器,因此切換到''「」「...」「」'將無濟於事。 – kennytm 2010-10-04 08:50:04