Dear all,
I was trying out OptionParser() and didn't quite understand who to use it correctly. This is my sample script:
#!/bin/env python
from time import strftime
from calendar import month_abbr
from optparse import OptionParser
# Set the CL options
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon", default=strftime("%m"))
parser.add_option("-u", "--user", type="string",
help="name of the user",
dest="vos")
options, arguments = parser.parse_args()
abbrMonth = tuple(month_abbr)[int(options.mon)]
def optMon():
print "The month is: %s" % abbrMonth
def optVos():
print "My name is: %s" % options.vos
def optMonVos():
print "I'm '%s' and this month is '%s'" % (options.vos,abbrMonth)
if options.mon:
optMon()
if options.vos:
optVos()
if options.mon and options.vos:
optMonVos()
This is what I'm trying to do:
- run the script without any option, will return optMon() with default value
- run the script with -m option, with return optMon() with gaven value
- run the script with ONLY -v option, will ONLY return optVos() with given value
- run the script with -m and -v opting, will return optMonVos() with given values.
But this is what I get if I run the script:
# ./test.py
The month is: Feb
#
# ./test.py -m 12
The month is: Dec
#
# ./test.py -m 3 -u Mac
The month is: Mar
My name is: Mac
I'm 'Mac' and this month is 'Mar'
#
# ./test.py -u Mac
The month is: Feb
My name is: Mac
I'm 'Mac' and this month is 'Feb'
The options.mon
is always returned default value, regardless of what are the options are given. what am I doing worng? Or it;s not possible at all?
Thanks in advance. Any help would be greatly appreciated. Cheers!!