tags:

views:

129

answers:

2

I am using the OptionParser from optparse module to parse my command that I get using the raw_input(). When I give a -h it displays the help screen and exits my application. I dont want it to display the help screen or exit the application. How can this be accomplished? Thanx in advance.

+5  A: 

set add_help_option to False

parser = optparse.OptionParser(add_help_option=False)
parser.add_option('-h', '--help', help='show this help message')
options, args = parser.parse_args()
if options.help:
   parser.print_help()

add_help_option (default: True)

If true, optparse will add a help option (with option strings "-h" and "--help") to the parser.

Nadia Alramli
thanx but, what if i dont want it to exit my application?
Sriram
@Sriram, check my updated answer
Nadia Alramli
got it! thanx.. please check my updated question too.. :)
Sriram
+4  A: 

optparse has a strange penchange for exiting your program, which I think is really unfortunate. You can initialize it like this to prevent it:

oparser = OptionParser(add_help_option=False, ...)

Note that now you have to handle the -h and --help options yourself. You can print the help message formatted by OptionParser like this:

print(oparser.format_help().strip())
Ned Batchelder
if add_help_option=False then can I assign -h to something else?
Sriram
Yes, once you turn off OptParser's help stuff, then you can do whatever you want with `-h` and `--help`.
Ned Batchelder