]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Lib/calendar.py
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 4/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Lib / calendar.py
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Lib/calendar.py b/AppPkg/Applications/Python/Python-2.7.10/Lib/calendar.py
new file mode 100644 (file)
index 0000000..f07cb71
--- /dev/null
@@ -0,0 +1,713 @@
+"""Calendar printing functions\r
+\r
+Note when comparing these calendars to the ones printed by cal(1): By\r
+default, these calendars have Monday as the first day of the week, and\r
+Sunday as the last (the European convention). Use setfirstweekday() to\r
+set the first day of the week (0=Monday, 6=Sunday)."""\r
+\r
+import sys\r
+import datetime\r
+import locale as _locale\r
+\r
+__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",\r
+           "firstweekday", "isleap", "leapdays", "weekday", "monthrange",\r
+           "monthcalendar", "prmonth", "month", "prcal", "calendar",\r
+           "timegm", "month_name", "month_abbr", "day_name", "day_abbr"]\r
+\r
+# Exception raised for bad input (with string parameter for details)\r
+error = ValueError\r
+\r
+# Exceptions raised for bad input\r
+class IllegalMonthError(ValueError):\r
+    def __init__(self, month):\r
+        self.month = month\r
+    def __str__(self):\r
+        return "bad month number %r; must be 1-12" % self.month\r
+\r
+\r
+class IllegalWeekdayError(ValueError):\r
+    def __init__(self, weekday):\r
+        self.weekday = weekday\r
+    def __str__(self):\r
+        return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday\r
+\r
+\r
+# Constants for months referenced later\r
+January = 1\r
+February = 2\r
+\r
+# Number of days per month (except for February in leap years)\r
+mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r
+\r
+# This module used to have hard-coded lists of day and month names, as\r
+# English strings.  The classes following emulate a read-only version of\r
+# that, but supply localized names.  Note that the values are computed\r
+# fresh on each call, in case the user changes locale between calls.\r
+\r
+class _localized_month:\r
+\r
+    _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]\r
+    _months.insert(0, lambda x: "")\r
+\r
+    def __init__(self, format):\r
+        self.format = format\r
+\r
+    def __getitem__(self, i):\r
+        funcs = self._months[i]\r
+        if isinstance(i, slice):\r
+            return [f(self.format) for f in funcs]\r
+        else:\r
+            return funcs(self.format)\r
+\r
+    def __len__(self):\r
+        return 13\r
+\r
+\r
+class _localized_day:\r
+\r
+    # January 1, 2001, was a Monday.\r
+    _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]\r
+\r
+    def __init__(self, format):\r
+        self.format = format\r
+\r
+    def __getitem__(self, i):\r
+        funcs = self._days[i]\r
+        if isinstance(i, slice):\r
+            return [f(self.format) for f in funcs]\r
+        else:\r
+            return funcs(self.format)\r
+\r
+    def __len__(self):\r
+        return 7\r
+\r
+\r
+# Full and abbreviated names of weekdays\r
+day_name = _localized_day('%A')\r
+day_abbr = _localized_day('%a')\r
+\r
+# Full and abbreviated names of months (1-based arrays!!!)\r
+month_name = _localized_month('%B')\r
+month_abbr = _localized_month('%b')\r
+\r
+# Constants for weekdays\r
+(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)\r
+\r
+\r
+def isleap(year):\r
+    """Return True for leap years, False for non-leap years."""\r
+    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\r
+\r
+\r
+def leapdays(y1, y2):\r
+    """Return number of leap years in range [y1, y2).\r
+       Assume y1 <= y2."""\r
+    y1 -= 1\r
+    y2 -= 1\r
+    return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)\r
+\r
+\r
+def weekday(year, month, day):\r
+    """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),\r
+       day (1-31)."""\r
+    return datetime.date(year, month, day).weekday()\r
+\r
+\r
+def monthrange(year, month):\r
+    """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for\r
+       year, month."""\r
+    if not 1 <= month <= 12:\r
+        raise IllegalMonthError(month)\r
+    day1 = weekday(year, month, 1)\r
+    ndays = mdays[month] + (month == February and isleap(year))\r
+    return day1, ndays\r
+\r
+\r
+class Calendar(object):\r
+    """\r
+    Base calendar class. This class doesn't do any formatting. It simply\r
+    provides data to subclasses.\r
+    """\r
+\r
+    def __init__(self, firstweekday=0):\r
+        self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday\r
+\r
+    def getfirstweekday(self):\r
+        return self._firstweekday % 7\r
+\r
+    def setfirstweekday(self, firstweekday):\r
+        self._firstweekday = firstweekday\r
+\r
+    firstweekday = property(getfirstweekday, setfirstweekday)\r
+\r
+    def iterweekdays(self):\r
+        """\r
+        Return a iterator for one week of weekday numbers starting with the\r
+        configured first one.\r
+        """\r
+        for i in range(self.firstweekday, self.firstweekday + 7):\r
+            yield i%7\r
+\r
+    def itermonthdates(self, year, month):\r
+        """\r
+        Return an iterator for one month. The iterator will yield datetime.date\r
+        values and will always iterate through complete weeks, so it will yield\r
+        dates outside the specified month.\r
+        """\r
+        date = datetime.date(year, month, 1)\r
+        # Go back to the beginning of the week\r
+        days = (date.weekday() - self.firstweekday) % 7\r
+        date -= datetime.timedelta(days=days)\r
+        oneday = datetime.timedelta(days=1)\r
+        while True:\r
+            yield date\r
+            try:\r
+                date += oneday\r
+            except OverflowError:\r
+                # Adding one day could fail after datetime.MAXYEAR\r
+                break\r
+            if date.month != month and date.weekday() == self.firstweekday:\r
+                break\r
+\r
+    def itermonthdays2(self, year, month):\r
+        """\r
+        Like itermonthdates(), but will yield (day number, weekday number)\r
+        tuples. For days outside the specified month the day number is 0.\r
+        """\r
+        for date in self.itermonthdates(year, month):\r
+            if date.month != month:\r
+                yield (0, date.weekday())\r
+            else:\r
+                yield (date.day, date.weekday())\r
+\r
+    def itermonthdays(self, year, month):\r
+        """\r
+        Like itermonthdates(), but will yield day numbers. For days outside\r
+        the specified month the day number is 0.\r
+        """\r
+        for date in self.itermonthdates(year, month):\r
+            if date.month != month:\r
+                yield 0\r
+            else:\r
+                yield date.day\r
+\r
+    def monthdatescalendar(self, year, month):\r
+        """\r
+        Return a matrix (list of lists) representing a month's calendar.\r
+        Each row represents a week; week entries are datetime.date values.\r
+        """\r
+        dates = list(self.itermonthdates(year, month))\r
+        return [ dates[i:i+7] for i in range(0, len(dates), 7) ]\r
+\r
+    def monthdays2calendar(self, year, month):\r
+        """\r
+        Return a matrix representing a month's calendar.\r
+        Each row represents a week; week entries are\r
+        (day number, weekday number) tuples. Day numbers outside this month\r
+        are zero.\r
+        """\r
+        days = list(self.itermonthdays2(year, month))\r
+        return [ days[i:i+7] for i in range(0, len(days), 7) ]\r
+\r
+    def monthdayscalendar(self, year, month):\r
+        """\r
+        Return a matrix representing a month's calendar.\r
+        Each row represents a week; days outside this month are zero.\r
+        """\r
+        days = list(self.itermonthdays(year, month))\r
+        return [ days[i:i+7] for i in range(0, len(days), 7) ]\r
+\r
+    def yeardatescalendar(self, year, width=3):\r
+        """\r
+        Return the data for the specified year ready for formatting. The return\r
+        value is a list of month rows. Each month row contains up to width months.\r
+        Each month contains between 4 and 6 weeks and each week contains 1-7\r
+        days. Days are datetime.date objects.\r
+        """\r
+        months = [\r
+            self.monthdatescalendar(year, i)\r
+            for i in range(January, January+12)\r
+        ]\r
+        return [months[i:i+width] for i in range(0, len(months), width) ]\r
+\r
+    def yeardays2calendar(self, year, width=3):\r
+        """\r
+        Return the data for the specified year ready for formatting (similar to\r
+        yeardatescalendar()). Entries in the week lists are\r
+        (day number, weekday number) tuples. Day numbers outside this month are\r
+        zero.\r
+        """\r
+        months = [\r
+            self.monthdays2calendar(year, i)\r
+            for i in range(January, January+12)\r
+        ]\r
+        return [months[i:i+width] for i in range(0, len(months), width) ]\r
+\r
+    def yeardayscalendar(self, year, width=3):\r
+        """\r
+        Return the data for the specified year ready for formatting (similar to\r
+        yeardatescalendar()). Entries in the week lists are day numbers.\r
+        Day numbers outside this month are zero.\r
+        """\r
+        months = [\r
+            self.monthdayscalendar(year, i)\r
+            for i in range(January, January+12)\r
+        ]\r
+        return [months[i:i+width] for i in range(0, len(months), width) ]\r
+\r
+\r
+class TextCalendar(Calendar):\r
+    """\r
+    Subclass of Calendar that outputs a calendar as a simple plain text\r
+    similar to the UNIX program cal.\r
+    """\r
+\r
+    def prweek(self, theweek, width):\r
+        """\r
+        Print a single week (no newline).\r
+        """\r
+        print self.formatweek(theweek, width),\r
+\r
+    def formatday(self, day, weekday, width):\r
+        """\r
+        Returns a formatted day.\r
+        """\r
+        if day == 0:\r
+            s = ''\r
+        else:\r
+            s = '%2i' % day             # right-align single-digit days\r
+        return s.center(width)\r
+\r
+    def formatweek(self, theweek, width):\r
+        """\r
+        Returns a single week in a string (no newline).\r
+        """\r
+        return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)\r
+\r
+    def formatweekday(self, day, width):\r
+        """\r
+        Returns a formatted week day name.\r
+        """\r
+        if width >= 9:\r
+            names = day_name\r
+        else:\r
+            names = day_abbr\r
+        return names[day][:width].center(width)\r
+\r
+    def formatweekheader(self, width):\r
+        """\r
+        Return a header for a week.\r
+        """\r
+        return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())\r
+\r
+    def formatmonthname(self, theyear, themonth, width, withyear=True):\r
+        """\r
+        Return a formatted month name.\r
+        """\r
+        s = month_name[themonth]\r
+        if withyear:\r
+            s = "%s %r" % (s, theyear)\r
+        return s.center(width)\r
+\r
+    def prmonth(self, theyear, themonth, w=0, l=0):\r
+        """\r
+        Print a month's calendar.\r
+        """\r
+        print self.formatmonth(theyear, themonth, w, l),\r
+\r
+    def formatmonth(self, theyear, themonth, w=0, l=0):\r
+        """\r
+        Return a month's calendar string (multi-line).\r
+        """\r
+        w = max(2, w)\r
+        l = max(1, l)\r
+        s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)\r
+        s = s.rstrip()\r
+        s += '\n' * l\r
+        s += self.formatweekheader(w).rstrip()\r
+        s += '\n' * l\r
+        for week in self.monthdays2calendar(theyear, themonth):\r
+            s += self.formatweek(week, w).rstrip()\r
+            s += '\n' * l\r
+        return s\r
+\r
+    def formatyear(self, theyear, w=2, l=1, c=6, m=3):\r
+        """\r
+        Returns a year's calendar as a multi-line string.\r
+        """\r
+        w = max(2, w)\r
+        l = max(1, l)\r
+        c = max(2, c)\r
+        colwidth = (w + 1) * 7 - 1\r
+        v = []\r
+        a = v.append\r
+        a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())\r
+        a('\n'*l)\r
+        header = self.formatweekheader(w)\r
+        for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):\r
+            # months in this row\r
+            months = range(m*i+1, min(m*(i+1)+1, 13))\r
+            a('\n'*l)\r
+            names = (self.formatmonthname(theyear, k, colwidth, False)\r
+                     for k in months)\r
+            a(formatstring(names, colwidth, c).rstrip())\r
+            a('\n'*l)\r
+            headers = (header for k in months)\r
+            a(formatstring(headers, colwidth, c).rstrip())\r
+            a('\n'*l)\r
+            # max number of weeks for this row\r
+            height = max(len(cal) for cal in row)\r
+            for j in range(height):\r
+                weeks = []\r
+                for cal in row:\r
+                    if j >= len(cal):\r
+                        weeks.append('')\r
+                    else:\r
+                        weeks.append(self.formatweek(cal[j], w))\r
+                a(formatstring(weeks, colwidth, c).rstrip())\r
+                a('\n' * l)\r
+        return ''.join(v)\r
+\r
+    def pryear(self, theyear, w=0, l=0, c=6, m=3):\r
+        """Print a year's calendar."""\r
+        print self.formatyear(theyear, w, l, c, m)\r
+\r
+\r
+class HTMLCalendar(Calendar):\r
+    """\r
+    This calendar returns complete HTML pages.\r
+    """\r
+\r
+    # CSS classes for the day <td>s\r
+    cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]\r
+\r
+    def formatday(self, day, weekday):\r
+        """\r
+        Return a day as a table cell.\r
+        """\r
+        if day == 0:\r
+            return '<td class="noday">&nbsp;</td>' # day outside month\r
+        else:\r
+            return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)\r
+\r
+    def formatweek(self, theweek):\r
+        """\r
+        Return a complete week as a table row.\r
+        """\r
+        s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)\r
+        return '<tr>%s</tr>' % s\r
+\r
+    def formatweekday(self, day):\r
+        """\r
+        Return a weekday name as a table header.\r
+        """\r
+        return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])\r
+\r
+    def formatweekheader(self):\r
+        """\r
+        Return a header for a week as a table row.\r
+        """\r
+        s = ''.join(self.formatweekday(i) for i in self.iterweekdays())\r
+        return '<tr>%s</tr>' % s\r
+\r
+    def formatmonthname(self, theyear, themonth, withyear=True):\r
+        """\r
+        Return a month name as a table row.\r
+        """\r
+        if withyear:\r
+            s = '%s %s' % (month_name[themonth], theyear)\r
+        else:\r
+            s = '%s' % month_name[themonth]\r
+        return '<tr><th colspan="7" class="month">%s</th></tr>' % s\r
+\r
+    def formatmonth(self, theyear, themonth, withyear=True):\r
+        """\r
+        Return a formatted month as a table.\r
+        """\r
+        v = []\r
+        a = v.append\r
+        a('<table border="0" cellpadding="0" cellspacing="0" class="month">')\r
+        a('\n')\r
+        a(self.formatmonthname(theyear, themonth, withyear=withyear))\r
+        a('\n')\r
+        a(self.formatweekheader())\r
+        a('\n')\r
+        for week in self.monthdays2calendar(theyear, themonth):\r
+            a(self.formatweek(week))\r
+            a('\n')\r
+        a('</table>')\r
+        a('\n')\r
+        return ''.join(v)\r
+\r
+    def formatyear(self, theyear, width=3):\r
+        """\r
+        Return a formatted year as a table of tables.\r
+        """\r
+        v = []\r
+        a = v.append\r
+        width = max(width, 1)\r
+        a('<table border="0" cellpadding="0" cellspacing="0" class="year">')\r
+        a('\n')\r
+        a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))\r
+        for i in range(January, January+12, width):\r
+            # months in this row\r
+            months = range(i, min(i+width, 13))\r
+            a('<tr>')\r
+            for m in months:\r
+                a('<td>')\r
+                a(self.formatmonth(theyear, m, withyear=False))\r
+                a('</td>')\r
+            a('</tr>')\r
+        a('</table>')\r
+        return ''.join(v)\r
+\r
+    def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):\r
+        """\r
+        Return a formatted year as a complete HTML page.\r
+        """\r
+        if encoding is None:\r
+            encoding = sys.getdefaultencoding()\r
+        v = []\r
+        a = v.append\r
+        a('<?xml version="1.0" encoding="%s"?>\n' % encoding)\r
+        a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')\r
+        a('<html>\n')\r
+        a('<head>\n')\r
+        a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)\r
+        if css is not None:\r
+            a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)\r
+        a('<title>Calendar for %d</title>\n' % theyear)\r
+        a('</head>\n')\r
+        a('<body>\n')\r
+        a(self.formatyear(theyear, width))\r
+        a('</body>\n')\r
+        a('</html>\n')\r
+        return ''.join(v).encode(encoding, "xmlcharrefreplace")\r
+\r
+\r
+class TimeEncoding:\r
+    def __init__(self, locale):\r
+        self.locale = locale\r
+\r
+    def __enter__(self):\r
+        self.oldlocale = _locale.getlocale(_locale.LC_TIME)\r
+        _locale.setlocale(_locale.LC_TIME, self.locale)\r
+        return _locale.getlocale(_locale.LC_TIME)[1]\r
+\r
+    def __exit__(self, *args):\r
+        _locale.setlocale(_locale.LC_TIME, self.oldlocale)\r
+\r
+\r
+class LocaleTextCalendar(TextCalendar):\r
+    """\r
+    This class can be passed a locale name in the constructor and will return\r
+    month and weekday names in the specified locale. If this locale includes\r
+    an encoding all strings containing month and weekday names will be returned\r
+    as unicode.\r
+    """\r
+\r
+    def __init__(self, firstweekday=0, locale=None):\r
+        TextCalendar.__init__(self, firstweekday)\r
+        if locale is None:\r
+            locale = _locale.getdefaultlocale()\r
+        self.locale = locale\r
+\r
+    def formatweekday(self, day, width):\r
+        with TimeEncoding(self.locale) as encoding:\r
+            if width >= 9:\r
+                names = day_name\r
+            else:\r
+                names = day_abbr\r
+            name = names[day]\r
+            if encoding is not None:\r
+                name = name.decode(encoding)\r
+            return name[:width].center(width)\r
+\r
+    def formatmonthname(self, theyear, themonth, width, withyear=True):\r
+        with TimeEncoding(self.locale) as encoding:\r
+            s = month_name[themonth]\r
+            if encoding is not None:\r
+                s = s.decode(encoding)\r
+            if withyear:\r
+                s = "%s %r" % (s, theyear)\r
+            return s.center(width)\r
+\r
+\r
+class LocaleHTMLCalendar(HTMLCalendar):\r
+    """\r
+    This class can be passed a locale name in the constructor and will return\r
+    month and weekday names in the specified locale. If this locale includes\r
+    an encoding all strings containing month and weekday names will be returned\r
+    as unicode.\r
+    """\r
+    def __init__(self, firstweekday=0, locale=None):\r
+        HTMLCalendar.__init__(self, firstweekday)\r
+        if locale is None:\r
+            locale = _locale.getdefaultlocale()\r
+        self.locale = locale\r
+\r
+    def formatweekday(self, day):\r
+        with TimeEncoding(self.locale) as encoding:\r
+            s = day_abbr[day]\r
+            if encoding is not None:\r
+                s = s.decode(encoding)\r
+            return '<th class="%s">%s</th>' % (self.cssclasses[day], s)\r
+\r
+    def formatmonthname(self, theyear, themonth, withyear=True):\r
+        with TimeEncoding(self.locale) as encoding:\r
+            s = month_name[themonth]\r
+            if encoding is not None:\r
+                s = s.decode(encoding)\r
+            if withyear:\r
+                s = '%s %s' % (s, theyear)\r
+            return '<tr><th colspan="7" class="month">%s</th></tr>' % s\r
+\r
+\r
+# Support for old module level interface\r
+c = TextCalendar()\r
+\r
+firstweekday = c.getfirstweekday\r
+\r
+def setfirstweekday(firstweekday):\r
+    try:\r
+        firstweekday.__index__\r
+    except AttributeError:\r
+        raise IllegalWeekdayError(firstweekday)\r
+    if not MONDAY <= firstweekday <= SUNDAY:\r
+        raise IllegalWeekdayError(firstweekday)\r
+    c.firstweekday = firstweekday\r
+\r
+monthcalendar = c.monthdayscalendar\r
+prweek = c.prweek\r
+week = c.formatweek\r
+weekheader = c.formatweekheader\r
+prmonth = c.prmonth\r
+month = c.formatmonth\r
+calendar = c.formatyear\r
+prcal = c.pryear\r
+\r
+\r
+# Spacing of month columns for multi-column year calendar\r
+_colwidth = 7*3 - 1         # Amount printed by prweek()\r
+_spacing = 6                # Number of spaces between columns\r
+\r
+\r
+def format(cols, colwidth=_colwidth, spacing=_spacing):\r
+    """Prints multi-column formatting for year calendars"""\r
+    print formatstring(cols, colwidth, spacing)\r
+\r
+\r
+def formatstring(cols, colwidth=_colwidth, spacing=_spacing):\r
+    """Returns a string formatted from n strings, centered within n columns."""\r
+    spacing *= ' '\r
+    return spacing.join(c.center(colwidth) for c in cols)\r
+\r
+\r
+EPOCH = 1970\r
+_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()\r
+\r
+\r
+def timegm(tuple):\r
+    """Unrelated but handy function to calculate Unix timestamp from GMT."""\r
+    year, month, day, hour, minute, second = tuple[:6]\r
+    days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1\r
+    hours = days*24 + hour\r
+    minutes = hours*60 + minute\r
+    seconds = minutes*60 + second\r
+    return seconds\r
+\r
+\r
+def main(args):\r
+    import optparse\r
+    parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]")\r
+    parser.add_option(\r
+        "-w", "--width",\r
+        dest="width", type="int", default=2,\r
+        help="width of date column (default 2, text only)"\r
+    )\r
+    parser.add_option(\r
+        "-l", "--lines",\r
+        dest="lines", type="int", default=1,\r
+        help="number of lines for each week (default 1, text only)"\r
+    )\r
+    parser.add_option(\r
+        "-s", "--spacing",\r
+        dest="spacing", type="int", default=6,\r
+        help="spacing between months (default 6, text only)"\r
+    )\r
+    parser.add_option(\r
+        "-m", "--months",\r
+        dest="months", type="int", default=3,\r
+        help="months per row (default 3, text only)"\r
+    )\r
+    parser.add_option(\r
+        "-c", "--css",\r
+        dest="css", default="calendar.css",\r
+        help="CSS to use for page (html only)"\r
+    )\r
+    parser.add_option(\r
+        "-L", "--locale",\r
+        dest="locale", default=None,\r
+        help="locale to be used from month and weekday names"\r
+    )\r
+    parser.add_option(\r
+        "-e", "--encoding",\r
+        dest="encoding", default=None,\r
+        help="Encoding to use for output"\r
+    )\r
+    parser.add_option(\r
+        "-t", "--type",\r
+        dest="type", default="text",\r
+        choices=("text", "html"),\r
+        help="output type (text or html)"\r
+    )\r
+\r
+    (options, args) = parser.parse_args(args)\r
+\r
+    if options.locale and not options.encoding:\r
+        parser.error("if --locale is specified --encoding is required")\r
+        sys.exit(1)\r
+\r
+    locale = options.locale, options.encoding\r
+\r
+    if options.type == "html":\r
+        if options.locale:\r
+            cal = LocaleHTMLCalendar(locale=locale)\r
+        else:\r
+            cal = HTMLCalendar()\r
+        encoding = options.encoding\r
+        if encoding is None:\r
+            encoding = sys.getdefaultencoding()\r
+        optdict = dict(encoding=encoding, css=options.css)\r
+        if len(args) == 1:\r
+            print cal.formatyearpage(datetime.date.today().year, **optdict)\r
+        elif len(args) == 2:\r
+            print cal.formatyearpage(int(args[1]), **optdict)\r
+        else:\r
+            parser.error("incorrect number of arguments")\r
+            sys.exit(1)\r
+    else:\r
+        if options.locale:\r
+            cal = LocaleTextCalendar(locale=locale)\r
+        else:\r
+            cal = TextCalendar()\r
+        optdict = dict(w=options.width, l=options.lines)\r
+        if len(args) != 3:\r
+            optdict["c"] = options.spacing\r
+            optdict["m"] = options.months\r
+        if len(args) == 1:\r
+            result = cal.formatyear(datetime.date.today().year, **optdict)\r
+        elif len(args) == 2:\r
+            result = cal.formatyear(int(args[1]), **optdict)\r
+        elif len(args) == 3:\r
+            result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)\r
+        else:\r
+            parser.error("incorrect number of arguments")\r
+            sys.exit(1)\r
+        if options.encoding:\r
+            result = result.encode(options.encoding)\r
+        print result\r
+\r
+\r
+if __name__ == "__main__":\r
+    main(sys.argv)\r