Python argparse: How to insert newline in the help text?
Try using RawTextHelpFormatter
:
from argparse import RawTextHelpFormatter
parser = 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 argparse
class 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 ArgumentParser
parser = 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 adding
the defaults to all options, and raw input of the utilities description. The full version
has 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, textwrap
parser = 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 information
Prepare input file
optional arguments:
-h, --help show this help message and exit
--argument ARGUMENT
First line
Second line
More lines ...