How to insert newlines on argparse help text?
Try using RawTextHelpFormatter
to preserve all of your formatting:
from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)
It's similar to RawDescriptionHelpFormatter
but instead of only applying to the description and epilog, RawTextHelpFormatter
also applies to all help text (including arguments).
Python argparse: How to insert newline the help text in subparser?
The subparsers.add_parser()
method takes the same ArgumentParser
constructor arguments as argparse.ArgumentParser()
. So, to use the RawTextHelpFormatter
for the subparser, you need to set the formatter_class
explicitly when you add the subparser.
>>> import argparse
>>> parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
>>> subparsers = parser.add_subparsers()
Change this line to set the formatter_class
of the subparser:
>>> parser_start = subparsers.add_parser('stop', formatter_class=argparse.RawTextHelpFormatter)
Now, your help text will contain the newlines:
>>> parser_start.add_argument("file", help="firstline\nnext line\nlast line")
_StoreAction(option_strings=[], dest='file', nargs=None, const=None, default=None, type=None, choices=None, help='firstline\nnext line\nlast line', metavar=None)
>>> print parser.parse_args(['stop', '--help'])
usage: stop [-h] file
positional arguments:
file firstline
next line
last line
optional arguments:
-h, --help show this help message and exit
Multiple lines in python argparse help display
The default help formatter re-wraps lines to fit your terminal (it looks at the COLUMNS
environment variable to determine the output width, defaulting to 80 characters total).
From the formatter_class
section:
By default,
ArgumentParser
objects line-wrap the description and epilog texts in command-line help messages.
Use the RawTextHelpFormatter
class instead to indicate that you already wrapped the lines:
RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions.
For your code that'd look like:
parser = argparse.ArgumentParser(description='details',
usage='use "%(prog)s --help" for more information',
formatter_class=argparse.RawTextHelpFormatter)
Do watch out you don't add too many newlines; triple-quoted strings include the newlines you leave in the string. As such you don't need the \n
characters:
>>> import argparse
>>> parser = argparse.ArgumentParser(description='details',
... usage='use "%(prog)s --help" for more information',
... formatter_class=argparse.RawTextHelpFormatter)
>>> parser.add_argument('--argument', default=None,
... help='''
... First line
... Second line
...
... More lines
... ''')
_StoreAction(option_strings=['--argument'], dest='argument', nargs=None, const=None, default=None, type=None, choices=None, help='\n First line\n Second line\n\n More lines\n ', metavar=None)
>>> parser.print_help()
usage: use " --help" for more information
details
optional arguments:
-h, --help show this help message and exit
--argument ARGUMENT
First line
Second line
More lines
Parse text with newline using argparse
Your \n
is taken as \
followed by n
and not interpreted as it should. Use a command like echo
or printf
to correctly interpret it. This should work on almost any shell (sh
, bash
, zsh
, etc).
$ ./newline2argparse.py "$(echo -en 'line1\nline2')"
$ ./newline2argparse.py "$(printf 'line1\nline2')"
$ ./newline2argparse.py `printf "line1\nline2"`
There are plenty of alternatives.
Python argparse: Insert blank line between help entries
You can create your own help text formatter that does this. Note that this requires you to be very specific to the implementation detail of the argparse.HelpFormatter
. So consider this warning that is included in every help formatter type description:
Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.
Once we ignore that, creating our own help formatter that adds a blank line between the entries is very simple:
class BlankLinesHelpFormatter (argparse.HelpFormatter):
def _split_lines(self, text, width):
return super()._split_lines(text, width) + ['']
And that’s it. Now when you create the ArgumentParser
object while passing
to the constructor, blank lines will appear between each argument in the help text.
formatter_class=BlankLinesHelpFormatter
Python argparse - help text for long argument name
The HelpFormatter
class takes a max_help_position
argument. The default value is 24, which is what you are seeing in the help.
It can be changed with a new Formatter subclass, or modification to the calling argument.
In [23]: parser.formatter_class =
lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=30)
Here I'm modifying the formatter_class
attribute after, but you could instead use this lambda
line in place of
formatter_class=argparse.RawTextHelpFormatter
The result is:
In [24]: parser.print_help()
usage: ipython3 [-h] [-bs] [-so] [-ci] [-desc]
Select one of the options given
optional arguments:
-h, --help show this help message and exit
-bs , --business_service choose the service
-so , --service_offering
-ci , --mdcb_ci provide configuration item
-desc , --description write description
Parameters like this were chosen to balance overall width of the display with legibility. They can be tweaked like this, but it does require some Python programming knowledge. It's been a while since I did this, so my suggestion might not be the simplest. But it's generally in the right direction.
Another way of setting it with the partial
wrapper:
In [42]: from functools import partial
In [43]: newformatter=partial(argparse.HelpFormatter, max_help_position=30)
In [44]: parser.formatter_class=newformatter
Argparse, displaying custom help text without any of the boilerplate argparse text
You can use sys.exit()
after the help text has been displayed, and before the parsing has begun, to avoid problems with "-h not recognized".
So anywhere before the line
# Parse the arguments and call appropriate functions
add
if len(sys.argv) == 1 or '-h' in sys.argv or '--help' in sys.argv:
print(help_text)
sys.exit(1)
In situations where that is not good enough you can subclass argparse.HelpFormatter
like so
usage_help_str = 'myscript command [options]'
epilog_str = "More info can be found at https://..."
class Formatter(argparse.HelpFormatter):
# override methods and stuff
def formatter(prog):
return Formatter(prog)
parser = argparse.ArgumentParser(formatter_class=formatter, epilog=epilog_str, usage=usage_help_str, add_help=False)
I tried looking around for documentation on subclassing the helpFormatter, but I couldn't find anything. It looks like people are just looking at the source code to figure out how to subclass it.
Python Argparse - How can I add text to the default help message?
You can quite do it using epilog.
Here is an example below:
import argparse
import textwrap
parser = argparse.ArgumentParser(
prog='ProgramName',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''\
additional information:
I have indented it
exactly the way
I want it
'''))
parser.add_argument('--foo', nargs='?', help='foo help')
parser.add_argument('bar', nargs='+', help='bar help')
parser.print_help()
Result :
usage: ProgramName [-h] [--foo [FOO]] bar [bar ...]
positional arguments:
bar bar help
optional arguments:
-h, --help show this help message and exit
--foo [FOO] foo help
additional information:
I have indented it
exactly the way
I want it
Related Topics
How to Efficiently Calculate a Running Standard Deviation
How to Perform HTML Decoding/Encoding Using Python/Django
Convert Image from Pil to Opencv Format
Calculating Arithmetic Mean (One Type of Average) in Python
Angles Between Two N-Dimensional Vectors in Python
Matplotlib: Overlay Plots with Different Scales
How to Enumerate an Object's Properties in Python
Schedule Python Script - Windows 7
Right Way to Reverse a Pandas Dataframe
Python: Syntaxerror: Eol While Scanning String Literal
How to Give a Pandas/Matplotlib Bar Graph Custom Colors
Check If String Contains Only Whitespace
Fastest Way to Grow a Numpy Numeric Array
Extract Elements of List at Odd Positions
How to Decorate All Functions of a Class Without Typing It Over and Over for Each Method
Parsing HTML in Python - Lxml or Beautifulsoup? Which of These Is Better for What Kinds of Purposes