displaying newlines in the help message when using python's optparse
Asked Answered
R

3

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)
Rawlins answered 11/5, 2011 at 8:12 Comment(3)
Just as a side note. Why can't you use argparse? its far superiorLarisalarissa
Jakob, is there a way that I could use argparse when I'm using python 2.6 and want to share it with people who may or may not be using python 2.7+?Rawlins
pypi.python.org/pypi/argparse/1.2.1 Just include it locally ^^Larisalarissa
T
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
Tremolo answered 11/5, 2011 at 8:23 Comment(2)
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.Worldwide
There's a format_help() method that can be overridden, as well.Tremolo
D
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. :)

Dammar answered 1/4, 2014 at 14:44 Comment(0)
G
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.

Gaffney answered 13/9, 2016 at 0:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.