is possible to make own help messag开发者_如何转开发e or attach own event on help option using optparse module in Python?
Sure - just use the params to the OptionParser constructor:
import optparse
help_text = """
Hi, this is a really long help message for %prog.
It's a pretty ace thing. (C)2010 Stuff etc.
"""
parser = optparse.OptionParser(usage=help_text, version="%prog 1.0 beta")
(options, args) = parser.parse_args()
For custom help messages I ignore optparse altogether:
import os
import sys
from optparse import OptionParser
__version__ = '1.0'
progname = os.path.basename(sys.argv[0])
usage = """\
usage: %s [options] URL
options:
--pprint (default)
-h --help
--version
""" % progname
if __name__ == "__main__":
if len(sys.argv) < 2 or "-h" in sys.argv or "--help" in sys.argv:
sys.exit(usage)
if "--version" in sys.argv:
sys.exit(progname + " " + __version__)
parser = OptionParser()
parser.add_option("--pprint", action='store_true', default=True)
(options, args) = parser.parse_args()
print(options, args)
You should be able to replace the default help mechanism with your own merely by subclassing OptionParser
and overriding the print_help()
method.
精彩评论