argparse 中的帮助字符串,每个字符串来自新行

Helpstring in argparse, each string from new line

我正在做一个 CLI 实用程序。当在控制台中使用 -- help 函数添加文档字符串以调用模块的帮助时,我遇到了这样一个事实,即所有添加的文本都显示为连续的、牢不可破的消息。如何将字符串彼此分开?我试图在行尾添加 \n,但这不起作用。

def createParser():
    parser = argparse.ArgumentParser(
        prog='samplefind',
        description="""
        Script to search for matches by word or lines in a text file and save the found information in a new outfile.txt file.
        From command line run python sfind.py .
        To view all available options: python sfind.py -h .
        """

使用formatter_class=argparse.RawTextHelpFormatter 保留帮助字符串中的所有空格。这是 argparse 应用程序帮助字符串,而不是 docstring。虽然看起来有点难看:

parser = argparse.ArgumentParser(
        prog='samplefind',
        formatter_class=argparse.RawTextHelpFormatter,
        description="""
        Script to search for matches by word or lines in a text file and save the found information in a new outfile.txt file.
        From command line run python sfind.py .
        To view all available options: python sfind.py -h .
        """)

来自终端:

py bla.py -h usage: samplefind [-h]

    Script to search for matches by word or lines in a text file and save the found information in a new outfile.txt file.
    From command line run python sfind.py .
    To view all available options: python sfind.py -h .

请注意,这包括从行首开始的空格、新行以及所有内容。