6

I'm using the optparse module for option/argument parsing. For backwards compatibility reasons, I can't use the argparse module. How can I format my epilog message so that newlines are preserved?

In the below example, I'd like the epilog to be printed as formatted.

    epi = \
"""
Examples usages:
  Do something
  %prog -a -b foo
  Do something else
  %prog -d -f -h bar
"""
    parser = optparse.OptionParser(epilog=epi)
DannyTree
  • 1,137
  • 2
  • 12
  • 16

3 Answers3

8

See the first answer at:

python optparse, how to include additional info in usage output?

The basic answer is to subclass the OptionParser

class MyParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog
Community
  • 1
  • 1
  • How can you instead modify the help messages associated with the options? Then this answer doesn't work, since it only changes the formatting of the epilog. – HelloGoodbye Jan 29 '14 at 14:27
  • There's a format_help() method that can be overridden, as well. –  Jan 30 '14 at 19:09
1

You could decorate the optparse.HelpFormatter.format_description function:

from optparse import HelpFormatter as fmt
def decorate(fn):
    def wrapped(self=None, desc=""):
        return '\n'.join( [ fn(self, s).rstrip() for s in desc.split('\n') ] )
    return wrapped
fmt.format_description = decorate(fmt.format_description)

Thus, you can have a help description that does things like this:

my_desc = """This is some text
that wraps to some more stuff.\n
\n
And this is a new paragraph.\n
\n
This line comes before\n
this line but not in a different paragraph."""

Works for me. :)

1

For those of you who are using user227667's answer but want to replace %prog in the epilog, you may use:

class MyParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.expand_prog_name(self.epilog)

But in general, if possible, do not use optparse.

xiaket
  • 1,903
  • 1
  • 14
  • 8