Search code examples
pythonoptparse

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


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)

Solution

  • 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