Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)
edited by

I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.

from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',

    help="Some option, where\n"

         " a = alpha\n"

         " b = beta\n"

         " g = gamma\n"

         " d = delta\n"

         " e = epsilon")

parser.parse_args()

However, argparse strips all newlines and consecutive spaces. The result looks like

~/Downloads:52$ python2.7 x.py -h

usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:

  -h, --help      show this help message and exit

  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e

                  = epsilon

How do I insert newlines in the helptext.

2 Answers

0 votes
by (16.8k points)

Try using RawTextHelpFormatter here:

from argparse import RawTextHelpFormatter

parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

0 votes
by (340 points)

The argparse module does strip out newlines in help text in Python 2.7. To maintain formatting with newlines you have to use the text wrap module to format.

Code:

from argparse import ArgumentParser
import textwrap

parser = ArgumentParser(description='test')
help_text = "Some option, where:\n" + \
"\n".join([
" a = alpha",
" b = beta",
" g = gamma",
" d = delta",
" e = epsilon"
])

help_text = textwrap.dedent(help_text)

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a', help=help_text)
args = parser.parse_args()

In the above code help text is constructed using list of strings joined by new lines. This helps maintain the required format.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...