I have these below lines in my program
parser = OptionParser()
parser.add_option("-t","--TIMEOUT", dest="timeout", type="int", help="timeout in seconds")
if parser.has_option("-t") and options.timeout<=0:
print "Timeout if specified must be greater than zero"
sys.exit(CLI_ERROR)
That print statement above is being printed because parser.has_option("-t") is evaluating to true even if no -t option is specified to this script. Am I missing something here. Thanks in advance for your help.
You have to actually parse the options first. parser.has_option
just checks to see if the parser understands the given option (which it does, since you used add_option
to add it).
Thus, use
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t","--TIMEOUT", dest="timeout", type="int", help="timeout in seconds")
options, args = parser.parse_args()
if options.timeout is not None and options.timeout <= 0:
print "Timeout if specified must be greater than zero"
sys.exit(CLI_ERROR)