I use optparse module to parse the options that I make, 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