Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert newlines on argparse help text?

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?

like image 548
kennytm Avatar asked Oct 04 '10 08:10

kennytm


People also ask

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

Can you use Argparse in Jupyter notebook?

Basic usage of argparse in jupyter notebookWhen using argparse module in jupyter notebook, all required flag should be False . Before calling parser. parse_args() , we should declare as follows.


1 Answers

Try using RawTextHelpFormatter:

from argparse import RawTextHelpFormatter parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter) 
like image 149
Michał Kwiatkowski Avatar answered Sep 19 '22 07:09

Michał Kwiatkowski