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

北慕城南 提交于 2019-12-08 21:57:26

问题


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)

回答1:


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



回答2:


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. :)




回答3:


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.



来源:https://stackoverflow.com/questions/5961160/displaying-newlines-in-the-help-message-when-using-pythons-optparse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!