Usage message string that optparse makes in python?
I use optparse module to parse the options that I ma开发者_如何学运维ke, and it automatically generates usage message to print with -h option.
How can I get the usage message as a string in a python script? I'd like to print out it when something's wrong with parsing.
If you use parser.error(...)
(where parser
is your OptionParser
object) you'll get your usage message.
For example:
from optparse import OptionParser
parser = OptionParser('usage: %prog [options] target source [source ...]')
[...]
(opts, args) = parser.parse_args()
if len(args) < 2:
parser.error('need a target and at least one source')
produces:
Usage: merge-into.py [options] target source [source ...]
merge-into.py: error: need a target and at least one source
How about parser.format_help()
?
精彩评论