1
votes

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.

2
Unrelated: optparse is deprecated since 2.7 (replaced by argparse) - miku
Yeah, I was going to say that - had to go back to some old code where I still used optparse :) - Nicholas Riley
If you can use argparse depends on the python version you need to support… - Arne Babenhauserheide

2 Answers

2
votes

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
1
votes

How about parser.format_help()?