Hi Guys,
I'm playing with Python 2.6 and its optparse module. I would like to convert one of my arguments to a datetime through a callback but it fails.
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 get an error File: optparse.py in _check_callback "callback not callable"
. I guess I'm doing something wrong in the way I define my callback but what ? and why ? Can anyone help ?
UPDATE: As I said in my comment, I think the best way to have a datetime in the options of a command line script is by extending optparse as suggested in the python doc
the following class really works fine for that:
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, many thanks for the help!