使用python的optparse时在帮助消息中显示换行符
我正在使用optparse模块进行选项/参数分析。出于向后兼容性的原因,我无法使用argparse模块。我如何格式化我的epilog消息,以便保留换行符?使用python的optparse时在帮助消息中显示换行符
在下面的示例中,我希望将epilog打印为格式。
epi = \
"""
Examples usages:
Do something
%prog -a -b foo
Do something else
%prog -d -f -h bar
"""
parser = optparse.OptionParser(epilog=epi)
见第一个答案在:
python optparse, how to include additional info in usage output?
最基本的答案是继承OptionParser
class MyParser(optparse.OptionParser):
def format_epilog(self, formatter):
return self.epilog
谢谢。这正是我所期待的。 – DannyTree 2011-05-11 08:27:54
您怎样才能修改与选项相关的帮助信息?然后这个答案不起作用,因为它只会改变epilog的格式。 – HelloGoodbye 2014-01-29 14:27:47
还有一个format_help()方法也可以被覆盖。 – 2014-01-30 19:09:21
你可以装点optparse.HelpFormatter.format_description功能:
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)
因此,你可以有一个帮助说明,做这样的事情:
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."""
为我工作。 :)
对于那些你谁使用user227667的答案,但希望在结语更换%prog
,你可以使用:
class MyParser(optparse.OptionParser):
def format_epilog(self, formatter):
return self.expand_prog_name(self.epilog)
但在一般情况下,如果可能的话,请不要使用optparse。
正如旁注。为什么你不能使用argparse?它远远优于 – 2011-05-11 08:32:58
Jakob,有没有一种方法可以在我使用python 2.6时使用argparse,并且希望与可能使用或不使用Python 2.7+的人共享它? – DannyTree 2011-05-11 08:55:50
http://pypi.python.org/pypi/argparse/1.2.1只需在本地加入^^ – 2011-05-11 09:08:52