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?
开发者_如何学JAVAIn 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)
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
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. :)
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.
精彩评论