How to insert newlines on argparse help text? How to insert newlines on argparse help text? python python

How to insert newlines on argparse help text?


Try using RawTextHelpFormatter:

from argparse import RawTextHelpFormatterparser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)


If you just want to override the one option, you should not use RawTextHelpFormatter. Instead subclass the HelpFormatter and provide a special intro for the options that should be handled "raw" (I use "R|rest of help"):

import argparseclass SmartFormatter(argparse.HelpFormatter):    def _split_lines(self, text, width):        if text.startswith('R|'):            return text[2:].splitlines()          # this is the RawTextHelpFormatter._split_lines        return argparse.HelpFormatter._split_lines(self, text, width)

And use it:

from argparse import ArgumentParserparser = ArgumentParser(description='test', formatter_class=SmartFormatter)parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',    help="R|Some option, where\n"         " a = alpha\n"         " b = beta\n"         " g = gamma\n"         " d = delta\n"         " e = epsilon")parser.parse_args()

Any other calls to .add_argument() where the help does not start with R| will be wrapped as normal.

This is part of my improvements on argparse. The full SmartFormatter also supports addingthe defaults to all options, and raw input of the utilities description. The full versionhas its own _split_lines method, so that any formatting done to e.g. version strings is preserved:

parser.add_argument('--version', '-v', action="version",                    version="version...\n   42!")


Another easy way to do it is to include textwrap.

For example,

import argparse, textwrapparser = argparse.ArgumentParser(description='some information',        usage='use "python %(prog)s --help" for more information',        formatter_class=argparse.RawTextHelpFormatter)parser.add_argument('--argument', default=somedefault, type=sometype,        help= textwrap.dedent('''\        First line        Second line        More lines ... '''))

In this way, we can avoid the long empty space in front of each output line.

usage: use "python your_python_program.py --help" for more informationPrepare input fileoptional arguments:-h, --help            show this help message and exit--argument ARGUMENT                      First line                      Second line                      More lines ...


matomo