calendar.py 22.4 KB
Newer Older
1 2 3 4 5 6
"""Calendar printing functions

Note when comparing these calendars to the ones printed by cal(1): By
default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday)."""
Guido van Rossum's avatar
Guido van Rossum committed
7

8
from __future__ import with_statement
9
import sys, datetime, locale
Guido van Rossum's avatar
Guido van Rossum committed
10

11 12 13 14
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
           "firstweekday", "isleap", "leapdays", "weekday", "monthrange",
           "monthcalendar", "prmonth", "month", "prcal", "calendar",
           "timegm", "month_name", "month_abbr", "day_name", "day_abbr"]
15

16
# Exception raised for bad input (with string parameter for details)
17
error = ValueError
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
# Exceptions raised for bad input
class IllegalMonthError(ValueError):
    def __init__(self, month):
        self.month = month
    def __str__(self):
        return "bad month number %r; must be 1-12" % self.month


class IllegalWeekdayError(ValueError):
    def __init__(self, weekday):
        self.weekday = weekday
    def __str__(self):
        return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday


Guido van Rossum's avatar
Guido van Rossum committed
34 35 36 37 38
# Constants for months referenced later
January = 1
February = 2

# Number of days per month (except for February in leap years)
39
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Guido van Rossum's avatar
Guido van Rossum committed
40

41 42 43 44 45
# This module used to have hard-coded lists of day and month names, as
# English strings.  The classes following emulate a read-only version of
# that, but supply localized names.  Note that the values are computed
# fresh on each call, in case the user changes locale between calls.

46
class _localized_month:
47

48
    _months = [datetime.date(2001, i+1, 1).strftime for i in xrange(12)]
49 50
    _months.insert(0, lambda x: "")

51
    def __init__(self, format):
52
        self.format = format
53 54

    def __getitem__(self, i):
55 56 57 58 59
        funcs = self._months[i]
        if isinstance(i, slice):
            return [f(self.format) for f in funcs]
        else:
            return funcs(self.format)
60

61
    def __len__(self):
62 63
        return 13

64

65
class _localized_day:
66 67

    # January 1, 2001, was a Monday.
68
    _days = [datetime.date(2001, 1, i+1).strftime for i in xrange(7)]
69

70 71 72 73
    def __init__(self, format):
        self.format = format

    def __getitem__(self, i):
74 75 76 77 78
        funcs = self._days[i]
        if isinstance(i, slice):
            return [f(self.format) for f in funcs]
        else:
            return funcs(self.format)
79

80
    def __len__(self):
81
        return 7
82

83

Guido van Rossum's avatar
Guido van Rossum committed
84
# Full and abbreviated names of weekdays
85 86
day_name = _localized_day('%A')
day_abbr = _localized_day('%a')
Guido van Rossum's avatar
Guido van Rossum committed
87

88
# Full and abbreviated names of months (1-based arrays!!!)
89 90
month_name = _localized_month('%B')
month_abbr = _localized_month('%b')
Guido van Rossum's avatar
Guido van Rossum committed
91

92 93 94 95
# Constants for weekdays
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)


96
def isleap(year):
97
    """Return 1 for leap years, 0 for non-leap years."""
98
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Guido van Rossum's avatar
Guido van Rossum committed
99

100

101
def leapdays(y1, y2):
102
    """Return number of leap years in range [y1, y2).
103 104 105
       Assume y1 <= y2."""
    y1 -= 1
    y2 -= 1
106
    return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
Guido van Rossum's avatar
Guido van Rossum committed
107

108

Guido van Rossum's avatar
Guido van Rossum committed
109
def weekday(year, month, day):
110 111
    """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
       day (1-31)."""
112
    return datetime.date(year, month, day).weekday()
Guido van Rossum's avatar
Guido van Rossum committed
113

114

Guido van Rossum's avatar
Guido van Rossum committed
115
def monthrange(year, month):
116 117 118
    """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
       year, month."""
    if not 1 <= month <= 12:
119
        raise IllegalMonthError(month)
120 121 122
    day1 = weekday(year, month, 1)
    ndays = mdays[month] + (month == February and isleap(year))
    return day1, ndays
Guido van Rossum's avatar
Guido van Rossum committed
123

124 125 126 127 128 129 130 131

class Calendar(object):
    """
    Base calendar class. This class doesn't do any formatting. It simply
    provides data to subclasses.
    """

    def __init__(self, firstweekday=0):
132
        self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
133

134
    def getfirstweekday(self):
135
        return self._firstweekday % 7
136

137 138
    def setfirstweekday(self, firstweekday):
        self._firstweekday = firstweekday
139

140 141
    firstweekday = property(getfirstweekday, setfirstweekday)

142 143 144 145 146
    def iterweekdays(self):
        """
        Return a iterator for one week of weekday numbers starting with the
        configured first one.
        """
147
        for i in xrange(self.firstweekday, self.firstweekday + 7):
148 149 150 151 152 153 154 155 156 157
            yield i%7

    def itermonthdates(self, year, month):
        """
        Return an iterator for one month. The iterator will yield datetime.date
        values and will always iterate through complete weeks, so it will yield
        dates outside the specified month.
        """
        date = datetime.date(year, month, 1)
        # Go back to the beginning of the week
158
        days = (date.weekday() - self.firstweekday) % 7
159 160 161 162 163
        date -= datetime.timedelta(days=days)
        oneday = datetime.timedelta(days=1)
        while True:
            yield date
            date += oneday
164
            if date.month != month and date.weekday() == self.firstweekday:
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
                break

    def itermonthdays2(self, year, month):
        """
        Like itermonthdates(), but will yield (day number, weekday number)
        tuples. For days outside the specified month the day number is 0.
        """
        for date in self.itermonthdates(year, month):
            if date.month != month:
                yield (0, date.weekday())
            else:
                yield (date.day, date.weekday())

    def itermonthdays(self, year, month):
        """
        Like itermonthdates(), but will yield day numbers tuples. For days
        outside the specified month the day number is 0.
        """
        for date in self.itermonthdates(year, month):
            if date.month != month:
                yield 0
            else:
                yield date.day

    def monthdatescalendar(self, year, month):
        """
        Return a matrix (list of lists) representing a month's calendar.
        Each row represents a week; week entries are datetime.date values.
        """
        dates = list(self.itermonthdates(year, month))
        return [ dates[i:i+7] for i in xrange(0, len(dates), 7) ]

    def monthdays2calendar(self, year, month):
        """
        Return a matrix representing a month's calendar.
        Each row represents a week; week entries are
        (day number, weekday number) tuples. Day numbers outside this month
        are zero.
        """
        days = list(self.itermonthdays2(year, month))
        return [ days[i:i+7] for i in xrange(0, len(days), 7) ]

    def monthdayscalendar(self, year, month):
        """
        Return a matrix representing a month's calendar.
        Each row represents a week; days outside this month are zero.
        """
        days = list(self.itermonthdays(year, month))
        return [ days[i:i+7] for i in xrange(0, len(days), 7) ]

    def yeardatescalendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting. The return
        value is a list of month rows. Each month row contains upto width months.
        Each month contains between 4 and 6 weeks and each week contains 1-7
        days. Days are datetime.date objects.
        """
        months = [
            self.monthdatescalendar(year, i)
            for i in xrange(January, January+12)
        ]
        return [months[i:i+width] for i in xrange(0, len(months), width) ]

    def yeardays2calendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting (similar to
        yeardatescalendar()). Entries in the week lists are
        (day number, weekday number) tuples. Day numbers outside this month are
        zero.
        """
        months = [
            self.monthdays2calendar(year, i)
            for i in xrange(January, January+12)
        ]
        return [months[i:i+width] for i in xrange(0, len(months), width) ]

    def yeardayscalendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting (similar to
        yeardatescalendar()). Entries in the week lists are day numbers.
        Day numbers outside this month are zero.
        """
        months = [
            self.monthdayscalendar(year, i)
            for i in xrange(January, January+12)
        ]
        return [months[i:i+width] for i in xrange(0, len(months), width) ]


class TextCalendar(Calendar):
    """
    Subclass of Calendar that outputs a calendar as a simple plain text
    similar to the UNIX program cal.
    """

260
    def prweek(self, theweek, width):
261 262 263 264 265 266 267 268 269
        """
        Print a single week (no newline).
        """
        print self.week(theweek, width),

    def formatday(self, day, weekday, width):
        """
        Returns a formatted day.
        """
270 271 272 273
        if day == 0:
            s = ''
        else:
            s = '%2i' % day             # right-align single-digit days
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        return s.center(width)

    def formatweek(self, theweek, width):
        """
        Returns a single week in a string (no newline).
        """
        return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)

    def formatweekday(self, day, width):
        """
        Returns a formatted week day name.
        """
        if width >= 9:
            names = day_name
        else:
            names = day_abbr
        return names[day][:width].center(width)

    def formatweekheader(self, width):
        """
        Return a header for a week.
        """
        return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())

298
    def formatmonthname(self, theyear, themonth, width, withyear=True):
299 300 301
        """
        Return a formatted month name.
        """
302 303 304
        s = month_name[themonth]
        if withyear:
            s = "%s %r" % (s, theyear)
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        return s.center(width)

    def prmonth(self, theyear, themonth, w=0, l=0):
        """
        Print a month's calendar.
        """
        print self.formatmonth(theyear, themonth, w, l),

    def formatmonth(self, theyear, themonth, w=0, l=0):
        """
        Return a month's calendar string (multi-line).
        """
        w = max(2, w)
        l = max(1, l)
        s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
        s = s.rstrip()
        s += '\n' * l
        s += self.formatweekheader(w).rstrip()
        s += '\n' * l
        for week in self.monthdays2calendar(theyear, themonth):
            s += self.formatweek(week, w).rstrip()
            s += '\n' * l
        return s

    def formatyear(self, theyear, w=2, l=1, c=6, m=3):
        """
        Returns a year's calendar as a multi-line string.
        """
        w = max(2, w)
        l = max(1, l)
        c = max(2, c)
        colwidth = (w + 1) * 7 - 1
        v = []
        a = v.append
        a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
        a('\n'*l)
        header = self.formatweekheader(w)
        for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
            # months in this row
            months = xrange(m*i+1, min(m*(i+1)+1, 13))
            a('\n'*l)
346 347 348
            names = (self.formatmonthname(theyear, k, colwidth, False)
                     for k in months)
            a(formatstring(names, colwidth, c).rstrip())
349
            a('\n'*l)
350 351
            headers = (header for k in months)
            a(formatstring(headers, colwidth, c).rstrip())
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
            a('\n'*l)
            # max number of weeks for this row
            height = max(len(cal) for cal in row)
            for j in xrange(height):
                weeks = []
                for cal in row:
                    if j >= len(cal):
                        weeks.append('')
                    else:
                        weeks.append(self.formatweek(cal[j], w))
                a(formatstring(weeks, colwidth, c).rstrip())
                a('\n' * l)
        return ''.join(v)

    def pryear(self, theyear, w=0, l=0, c=6, m=3):
        """Print a year's calendar."""
        print self.formatyear(theyear, w, l, c, m)


class HTMLCalendar(Calendar):
    """
    This calendar returns complete HTML pages.
    """

    # CSS classes for the day <td>s
    cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

    def formatday(self, day, weekday):
        """
        Return a day as a table cell.
        """
        if day == 0:
            return '<td class="noday">&nbsp;</td>' # day outside month
        else:
            return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)

    def formatweek(self, theweek):
        """
        Return a complete week as a table row.
        """
        s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
        return '<tr>%s</tr>' % s

    def formatweekday(self, day):
        """
        Return a weekday name as a table header.
        """
        return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])

    def formatweekheader(self):
        """
        Return a header for a week as a table row.
        """
        s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
        return '<tr>%s</tr>' % s

    def formatmonthname(self, theyear, themonth, withyear=True):
        """
        Return a month name as a table row.
        """
        if withyear:
            s = '%s %s' % (month_name[themonth], theyear)
        else:
            s = '%s' % month_name[themonth]
        return '<tr><th colspan="7" class="month">%s</th></tr>' % s

    def formatmonth(self, theyear, themonth, withyear=True):
        """
        Return a formatted month as a table.
        """
        v = []
        a = v.append
        a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
        a('\n')
        a(self.formatmonthname(theyear, themonth, withyear=withyear))
        a('\n')
        a(self.formatweekheader())
        a('\n')
        for week in self.monthdays2calendar(theyear, themonth):
            a(self.formatweek(week))
            a('\n')
        a('</table>')
        a('\n')
        return ''.join(v)

    def formatyear(self, theyear, width=3):
        """
        Return a formatted year as a table of tables.
        """
        v = []
        a = v.append
        width = max(width, 1)
        a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
        a('\n')
        a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
        for i in xrange(January, January+12, width):
            # months in this row
            months = xrange(i, min(i+width, 13))
            a('<tr>')
            for m in months:
                a('<td>')
                a(self.formatmonth(theyear, m, withyear=False))
                a('</td>')
            a('</tr>')
        a('</table>')
        return ''.join(v)

    def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
        """
        Return a formatted year as a complete HTML page.
        """
        if encoding is None:
            encoding = sys.getdefaultencoding()
        v = []
        a = v.append
        a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
        a('<html>\n')
        a('<head>\n')
        a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
        if css is not None:
            a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
        a('<title>Calendar for %d</title\n' % theyear)
        a('</head>\n')
        a('<body>\n')
        a(self.formatyear(theyear, width))
        a('</body>\n')
        a('</html>\n')
480 481 482
        return ''.join(v).encode(encoding, "xmlcharrefreplace")


483 484 485 486 487 488 489 490 491 492 493 494
class TimeEncoding:
    def __init__(self, locale):
        self.locale = locale

    def __enter__(self):
        self.oldlocale = locale.setlocale(locale.LC_TIME, self.locale)
        return locale.getlocale(locale.LC_TIME)[1]

    def __exit__(self, *args):
        locale.setlocale(locale.LC_TIME, self.oldlocale)


495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
class LocaleTextCalendar(TextCalendar):
    """
    This class can be passed a locale name in the constructor and will return
    month and weekday names in the specified locale. If this locale includes
    an encoding all strings containing month and weekday names will be returned
    as unicode.
    """

    def __init__(self, firstweekday=0, locale=None):
        TextCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = locale.getdefaultlocale()
        self.locale = locale

    def formatweekday(self, day, width):
510
        with TimeEncoding(self.locale) as encoding:
511 512 513 514 515 516 517
            if width >= 9:
                names = day_name
            else:
                names = day_abbr
            name = names[day]
            if encoding is not None:
                name = name.decode(encoding)
518
            return name[:width].center(width)
519 520

    def formatmonthname(self, theyear, themonth, width, withyear=True):
521
        with TimeEncoding(self.locale) as encoding:
522 523 524 525 526
            s = month_name[themonth]
            if encoding is not None:
                s = s.decode(encoding)
            if withyear:
                s = "%s %r" % (s, theyear)
527
            return s.center(width)
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543


class LocaleHTMLCalendar(HTMLCalendar):
    """
    This class can be passed a locale name in the constructor and will return
    month and weekday names in the specified locale. If this locale includes
    an encoding all strings containing month and weekday names will be returned
    as unicode.
    """
    def __init__(self, firstweekday=0, locale=None):
        HTMLCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = locale.getdefaultlocale()
        self.locale = locale

    def formatweekday(self, day):
544
        with TimeEncoding(self.locale) as encoding:
545 546 547
            s = day_abbr[day]
            if encoding is not None:
                s = s.decode(encoding)
548
            return '<th class="%s">%s</th>' % (self.cssclasses[day], s)
549 550

    def formatmonthname(self, theyear, themonth, withyear=True):
551
        with TimeEncoding(self.locale) as encoding:
552 553 554 555 556
            s = month_name[themonth]
            if encoding is not None:
                s = s.decode(encoding)
            if withyear:
                s = '%s %s' % (s, theyear)
557
            return '<tr><th colspan="7" class="month">%s</th></tr>' % s
558 559 560 561 562


# Support for old module level interface
c = TextCalendar()

563
firstweekday = c.getfirstweekday
564 565 566 567 568 569

def setfirstweekday(firstweekday):
    if not MONDAY <= firstweekday <= SUNDAY:
        raise IllegalWeekdayError(firstweekday)
    c.firstweekday = firstweekday

570 571 572 573 574 575 576 577 578 579 580
monthcalendar = c.monthdayscalendar
prweek = c.prweek
week = c.formatweek
weekheader = c.formatweekheader
prmonth = c.prmonth
month = c.formatmonth
calendar = c.formatyear
prcal = c.pryear


# Spacing of month columns for multi-column year calendar
581
_colwidth = 7*3 - 1         # Amount printed by prweek()
582
_spacing = 6                # Number of spaces between columns
Guido van Rossum's avatar
Guido van Rossum committed
583

584 585 586 587 588 589 590 591 592 593 594

def format(cols, colwidth=_colwidth, spacing=_spacing):
    """Prints multi-column formatting for year calendars"""
    print formatstring(cols, colwidth, spacing)


def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
    """Returns a string formatted from n strings, centered within n columns."""
    spacing *= ' '
    return spacing.join(c.center(colwidth) for c in cols)

595

596
EPOCH = 1970
597 598
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()

599

600
def timegm(tuple):
601 602
    """Unrelated but handy function to calculate Unix timestamp from GMT."""
    year, month, day, hour, minute, second = tuple[:6]
603
    days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
604 605 606 607
    hours = days*24 + hour
    minutes = hours*60 + minute
    seconds = minutes*60 + second
    return seconds
608 609 610 611


def main(args):
    import optparse
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]")
    parser.add_option(
        "-w", "--width",
        dest="width", type="int", default=2,
        help="width of date column (default 2, text only)"
    )
    parser.add_option(
        "-l", "--lines",
        dest="lines", type="int", default=1,
        help="number of lines for each week (default 1, text only)"
    )
    parser.add_option(
        "-s", "--spacing",
        dest="spacing", type="int", default=6,
        help="spacing between months (default 6, text only)"
    )
    parser.add_option(
        "-m", "--months",
        dest="months", type="int", default=3,
        help="months per row (default 3, text only)"
    )
    parser.add_option(
        "-c", "--css",
        dest="css", default="calendar.css",
        help="CSS to use for page (html only)"
    )
    parser.add_option(
        "-L", "--locale",
        dest="locale", default=None,
        help="locale to be used from month and weekday names"
    )
    parser.add_option(
        "-e", "--encoding",
        dest="encoding", default=None,
        help="Encoding to use for output"
    )
    parser.add_option(
        "-t", "--type",
        dest="type", default="text",
        choices=("text", "html"),
        help="output type (text or html)"
    )
654 655 656

    (options, args) = parser.parse_args(args)

657 658 659 660
    if options.locale and not options.encoding:
        parser.error("if --locale is specified --encoding is required")
        sys.exit(1)

661
    if options.type == "html":
662 663 664 665
        if options.locale:
            cal = LocaleHTMLCalendar(locale=options.locale)
        else:
            cal = HTMLCalendar()
666 667 668 669 670 671 672 673 674 675 676 677
        encoding = options.encoding
        if encoding is None:
            encoding = sys.getdefaultencoding()
        optdict = dict(encoding=encoding, css=options.css)
        if len(args) == 1:
            print cal.formatyearpage(datetime.date.today().year, **optdict)
        elif len(args) == 2:
            print cal.formatyearpage(int(args[1]), **optdict)
        else:
            parser.error("incorrect number of arguments")
            sys.exit(1)
    else:
678 679 680 681
        if options.locale:
            cal = LocaleTextCalendar(locale=options.locale)
        else:
            cal = TextCalendar()
682 683 684 685 686
        optdict = dict(w=options.width, l=options.lines)
        if len(args) != 3:
            optdict["c"] = options.spacing
            optdict["m"] = options.months
        if len(args) == 1:
687
            result = cal.formatyear(datetime.date.today().year, **optdict)
688
        elif len(args) == 2:
689
            result = cal.formatyear(int(args[1]), **optdict)
690
        elif len(args) == 3:
691
            result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
692 693 694
        else:
            parser.error("incorrect number of arguments")
            sys.exit(1)
695 696 697
        if options.encoding:
            result = result.encode(options.encoding)
        print result
698 699 700 701


if __name__ == "__main__":
    main(sys.argv)