views:

62

answers:

1

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 to insert newlines in the help text?

+2  A: 

Try using RawTextHelpFormatter:

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)
Michał Kwiatkowski
Nice, thanks. Is it possible to apply it for 1 option only?
KennyTM
I think it's not. You could subclass it, but unfortunately `Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.` So probably not a great idea, although it might not matter, since 2.7 is meant to be the last 2.x python and you'll be expected to refactor lots of things for 3.x anyway. I'm actually running 2.6 with `argparse` installed via `easy_install` so that documentation may itself be out of date.
intuited