Search code examples
pythondocstring

Helpstring in argparse, each string from new line


I am doing a CLI utility. When adding a docstring to call help for the module with the function -- help in console, I was faced with the fact that all the added text is displayed as a continuous, unbreakable message. How to separate strings from each other? I tried to add \n at the end of the line, but this does not work.

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 .
        """

Solution

  • Use formatter_class=argparse.RawTextHelpFormatter to retain all spaces in your help string. This is the argparse application help string, not a docstring. Could look a bit ugly though:

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

    From terminal:

    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 .
    

    Do note that this include spaces from the beginning of line, new lines, everything.