Pb with callback in optparse python module
I am playing with Python 2.6 and its optparse module. I would like to convert one of my arguments to datetime via a callback, but it doesn't work.
Here is the code:
def parsedate(option, opt_str, value, parser):
option.date = datetime.strptime(value, "%Y/%m/%d")
def parse_options(args):
parser = OptionParser(usage="%prog -l LOGFOLDER [-e]", version="%prog 1.0")
parser.add_option("-d", "--date", action="callback", callback="parsedate", dest="date")
global options
(options, args) = parser.parse_args(args)
print options.date.strftime()
if __name__ == "__main__":
parse_options(sys.argv[1:])
I am getting an error File: optparse.py in _check_callback "callback not callable"
. I am probably doing something wrong in the way I define my callback, but what? and why? Can anyone please help?
UPDATE . As I said in my comment, I believe that the best way to have datetime in command line parameters of a script is to extend optparse as suggested in the python doc
the following class is really great for this:
from copy import copy
from optparse import Option, OptionValueError
from datetime import datetime
def check_date(option, opt, value):
try:
return datetime.strptime(value, "%Y/%m/%d")
except ValueError:
raise OptionValueError(
"option %s: invalid date value: %r. Should have a format like \"YYYY/MM/DD\"" % (opt, value))
class dateOption (Option):
TYPES = Option.TYPES + ("date",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["date"] = check_date
Anyway, thanks a lot for your help!
+2
source to share