Return long python strings correctly for optparse

How can I automatically wrap long lines of python so that they print correctly?

In particular, I am trying to add help lines with optparse that I want to easily modify.

I found several methods for working with long strings, none of which allow me to replenish after making changes using Mq in emacs or similar:

p.add_option('-a', help = "this is my\ long help text") 

forces new lines in results and does not allow to fill

 p.add_option('-a', help = "this is my " "long help text") 

but does not allow reloading

 p.add_option('-a', help = ''' this is my long help text ''') 

wrong but allows recharge

 p.add_option('-a', help = dedent(''' this is my long help text ''')) 

- the best option I found, the formats are almost correct and allows you to refuel, but leads to additional space at the beginning of the line.

+4
source share
3 answers

Use argparse instead of optparse if you are using Python> = 2.7. He is dedent for you. You can simply:

 parser.add_argument('--argument', '-a', help=''' this is my long help text ''') 

Even if you use Python <2.7, you can install argparse from pypi.

Note that there is a way to suppress this auto-dedent behavior. The link given by @msw is actually a section about this.

+1
source

docs uses dedent , so it seems reasonable, especially if it works. If you want to reset the master space, you can:

 help = dedent(''' this is my long help text ''')[1:] 

although

 dedent(โ€ฆ).lstrip() 

may be more obvious.

+2
source

I am not 100% sure that refueling is, but here is what I usually use:

 p.add_option('-a', help = ("this is my " "long help text")) 

(note the extra bracket). Emacs builds the next line with the previous parenthesis open for me.

+1
source

All Articles