calendar.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. """Calendar printing functions
  2. Note when comparing these calendars to the ones printed by cal(1): By
  3. default, these calendars have Monday as the first day of the week, and
  4. Sunday as the last (the European convention). Use setfirstweekday() to
  5. set the first day of the week (0=Monday, 6=Sunday)."""
  6. import sys
  7. import datetime
  8. import locale as _locale
  9. __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
  10. "firstweekday", "isleap", "leapdays", "weekday", "monthrange",
  11. "monthcalendar", "prmonth", "month", "prcal", "calendar",
  12. "timegm", "month_name", "month_abbr", "day_name", "day_abbr"]
  13. # Exception raised for bad input (with string parameter for details)
  14. error = ValueError
  15. # Exceptions raised for bad input
  16. class IllegalMonthError(ValueError):
  17. def __init__(self, month):
  18. self.month = month
  19. def __str__(self):
  20. return "bad month number %r; must be 1-12" % self.month
  21. class IllegalWeekdayError(ValueError):
  22. def __init__(self, weekday):
  23. self.weekday = weekday
  24. def __str__(self):
  25. return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday
  26. # Constants for months referenced later
  27. January = 1
  28. February = 2
  29. # Number of days per month (except for February in leap years)
  30. mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  31. # This module used to have hard-coded lists of day and month names, as
  32. # English strings. The classes following emulate a read-only version of
  33. # that, but supply localized names. Note that the values are computed
  34. # fresh on each call, in case the user changes locale between calls.
  35. class _localized_month:
  36. _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
  37. _months.insert(0, lambda x: "")
  38. def __init__(self, format):
  39. self.format = format
  40. def __getitem__(self, i):
  41. funcs = self._months[i]
  42. if isinstance(i, slice):
  43. return [f(self.format) for f in funcs]
  44. else:
  45. return funcs(self.format)
  46. def __len__(self):
  47. return 13
  48. class _localized_day:
  49. # January 1, 2001, was a Monday.
  50. _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
  51. def __init__(self, format):
  52. self.format = format
  53. def __getitem__(self, i):
  54. funcs = self._days[i]
  55. if isinstance(i, slice):
  56. return [f(self.format) for f in funcs]
  57. else:
  58. return funcs(self.format)
  59. def __len__(self):
  60. return 7
  61. # Full and abbreviated names of weekdays
  62. day_name = _localized_day('%A')
  63. day_abbr = _localized_day('%a')
  64. # Full and abbreviated names of months (1-based arrays!!!)
  65. month_name = _localized_month('%B')
  66. month_abbr = _localized_month('%b')
  67. # Constants for weekdays
  68. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  69. def isleap(year):
  70. """Return True for leap years, False for non-leap years."""
  71. return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  72. def leapdays(y1, y2):
  73. """Return number of leap years in range [y1, y2).
  74. Assume y1 <= y2."""
  75. y1 -= 1
  76. y2 -= 1
  77. return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
  78. def weekday(year, month, day):
  79. """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
  80. day (1-31)."""
  81. return datetime.date(year, month, day).weekday()
  82. def monthrange(year, month):
  83. """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
  84. year, month."""
  85. if not 1 <= month <= 12:
  86. raise IllegalMonthError(month)
  87. day1 = weekday(year, month, 1)
  88. ndays = mdays[month] + (month == February and isleap(year))
  89. return day1, ndays
  90. class Calendar(object):
  91. """
  92. Base calendar class. This class doesn't do any formatting. It simply
  93. provides data to subclasses.
  94. """
  95. def __init__(self, firstweekday=0):
  96. self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
  97. def getfirstweekday(self):
  98. return self._firstweekday % 7
  99. def setfirstweekday(self, firstweekday):
  100. self._firstweekday = firstweekday
  101. firstweekday = property(getfirstweekday, setfirstweekday)
  102. def iterweekdays(self):
  103. """
  104. Return an iterator for one week of weekday numbers starting with the
  105. configured first one.
  106. """
  107. for i in range(self.firstweekday, self.firstweekday + 7):
  108. yield i%7
  109. def itermonthdates(self, year, month):
  110. """
  111. Return an iterator for one month. The iterator will yield datetime.date
  112. values and will always iterate through complete weeks, so it will yield
  113. dates outside the specified month.
  114. """
  115. date = datetime.date(year, month, 1)
  116. # Go back to the beginning of the week
  117. days = (date.weekday() - self.firstweekday) % 7
  118. date -= datetime.timedelta(days=days)
  119. oneday = datetime.timedelta(days=1)
  120. while True:
  121. yield date
  122. try:
  123. date += oneday
  124. except OverflowError:
  125. # Adding one day could fail after datetime.MAXYEAR
  126. break
  127. if date.month != month and date.weekday() == self.firstweekday:
  128. break
  129. def itermonthdays2(self, year, month):
  130. """
  131. Like itermonthdates(), but will yield (day number, weekday number)
  132. tuples. For days outside the specified month the day number is 0.
  133. """
  134. for date in self.itermonthdates(year, month):
  135. if date.month != month:
  136. yield (0, date.weekday())
  137. else:
  138. yield (date.day, date.weekday())
  139. def itermonthdays(self, year, month):
  140. """
  141. Like itermonthdates(), but will yield day numbers. For days outside
  142. the specified month the day number is 0.
  143. """
  144. for date in self.itermonthdates(year, month):
  145. if date.month != month:
  146. yield 0
  147. else:
  148. yield date.day
  149. def monthdatescalendar(self, year, month):
  150. """
  151. Return a matrix (list of lists) representing a month's calendar.
  152. Each row represents a week; week entries are datetime.date values.
  153. """
  154. dates = list(self.itermonthdates(year, month))
  155. return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
  156. def monthdays2calendar(self, year, month):
  157. """
  158. Return a matrix representing a month's calendar.
  159. Each row represents a week; week entries are
  160. (day number, weekday number) tuples. Day numbers outside this month
  161. are zero.
  162. """
  163. days = list(self.itermonthdays2(year, month))
  164. return [ days[i:i+7] for i in range(0, len(days), 7) ]
  165. def monthdayscalendar(self, year, month):
  166. """
  167. Return a matrix representing a month's calendar.
  168. Each row represents a week; days outside this month are zero.
  169. """
  170. days = list(self.itermonthdays(year, month))
  171. return [ days[i:i+7] for i in range(0, len(days), 7) ]
  172. def yeardatescalendar(self, year, width=3):
  173. """
  174. Return the data for the specified year ready for formatting. The return
  175. value is a list of month rows. Each month row contains up to width months.
  176. Each month contains between 4 and 6 weeks and each week contains 1-7
  177. days. Days are datetime.date objects.
  178. """
  179. months = [
  180. self.monthdatescalendar(year, i)
  181. for i in range(January, January+12)
  182. ]
  183. return [months[i:i+width] for i in range(0, len(months), width) ]
  184. def yeardays2calendar(self, year, width=3):
  185. """
  186. Return the data for the specified year ready for formatting (similar to
  187. yeardatescalendar()). Entries in the week lists are
  188. (day number, weekday number) tuples. Day numbers outside this month are
  189. zero.
  190. """
  191. months = [
  192. self.monthdays2calendar(year, i)
  193. for i in range(January, January+12)
  194. ]
  195. return [months[i:i+width] for i in range(0, len(months), width) ]
  196. def yeardayscalendar(self, year, width=3):
  197. """
  198. Return the data for the specified year ready for formatting (similar to
  199. yeardatescalendar()). Entries in the week lists are day numbers.
  200. Day numbers outside this month are zero.
  201. """
  202. months = [
  203. self.monthdayscalendar(year, i)
  204. for i in range(January, January+12)
  205. ]
  206. return [months[i:i+width] for i in range(0, len(months), width) ]
  207. class TextCalendar(Calendar):
  208. """
  209. Subclass of Calendar that outputs a calendar as a simple plain text
  210. similar to the UNIX program cal.
  211. """
  212. def prweek(self, theweek, width):
  213. """
  214. Print a single week (no newline).
  215. """
  216. print(self.formatweek(theweek, width), end=' ')
  217. def formatday(self, day, weekday, width):
  218. """
  219. Returns a formatted day.
  220. """
  221. if day == 0:
  222. s = ''
  223. else:
  224. s = '%2i' % day # right-align single-digit days
  225. return s.center(width)
  226. def formatweek(self, theweek, width):
  227. """
  228. Returns a single week in a string (no newline).
  229. """
  230. return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)
  231. def formatweekday(self, day, width):
  232. """
  233. Returns a formatted week day name.
  234. """
  235. if width >= 9:
  236. names = day_name
  237. else:
  238. names = day_abbr
  239. return names[day][:width].center(width)
  240. def formatweekheader(self, width):
  241. """
  242. Return a header for a week.
  243. """
  244. return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())
  245. def formatmonthname(self, theyear, themonth, width, withyear=True):
  246. """
  247. Return a formatted month name.
  248. """
  249. s = month_name[themonth]
  250. if withyear:
  251. s = "%s %r" % (s, theyear)
  252. return s.center(width)
  253. def prmonth(self, theyear, themonth, w=0, l=0):
  254. """
  255. Print a month's calendar.
  256. """
  257. print(self.formatmonth(theyear, themonth, w, l), end=' ')
  258. def formatmonth(self, theyear, themonth, w=0, l=0):
  259. """
  260. Return a month's calendar string (multi-line).
  261. """
  262. w = max(2, w)
  263. l = max(1, l)
  264. s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
  265. s = s.rstrip()
  266. s += '\n' * l
  267. s += self.formatweekheader(w).rstrip()
  268. s += '\n' * l
  269. for week in self.monthdays2calendar(theyear, themonth):
  270. s += self.formatweek(week, w).rstrip()
  271. s += '\n' * l
  272. return s
  273. def formatyear(self, theyear, w=2, l=1, c=6, m=3):
  274. """
  275. Returns a year's calendar as a multi-line string.
  276. """
  277. w = max(2, w)
  278. l = max(1, l)
  279. c = max(2, c)
  280. colwidth = (w + 1) * 7 - 1
  281. v = []
  282. a = v.append
  283. a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
  284. a('\n'*l)
  285. header = self.formatweekheader(w)
  286. for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
  287. # months in this row
  288. months = range(m*i+1, min(m*(i+1)+1, 13))
  289. a('\n'*l)
  290. names = (self.formatmonthname(theyear, k, colwidth, False)
  291. for k in months)
  292. a(formatstring(names, colwidth, c).rstrip())
  293. a('\n'*l)
  294. headers = (header for k in months)
  295. a(formatstring(headers, colwidth, c).rstrip())
  296. a('\n'*l)
  297. # max number of weeks for this row
  298. height = max(len(cal) for cal in row)
  299. for j in range(height):
  300. weeks = []
  301. for cal in row:
  302. if j >= len(cal):
  303. weeks.append('')
  304. else:
  305. weeks.append(self.formatweek(cal[j], w))
  306. a(formatstring(weeks, colwidth, c).rstrip())
  307. a('\n' * l)
  308. return ''.join(v)
  309. def pryear(self, theyear, w=0, l=0, c=6, m=3):
  310. """Print a year's calendar."""
  311. print(self.formatyear(theyear, w, l, c, m))
  312. class HTMLCalendar(Calendar):
  313. """
  314. This calendar returns complete HTML pages.
  315. """
  316. # CSS classes for the day <td>s
  317. cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
  318. def formatday(self, day, weekday):
  319. """
  320. Return a day as a table cell.
  321. """
  322. if day == 0:
  323. return '<td class="noday">&nbsp;</td>' # day outside month
  324. else:
  325. return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
  326. def formatweek(self, theweek):
  327. """
  328. Return a complete week as a table row.
  329. """
  330. s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
  331. return '<tr>%s</tr>' % s
  332. def formatweekday(self, day):
  333. """
  334. Return a weekday name as a table header.
  335. """
  336. return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])
  337. def formatweekheader(self):
  338. """
  339. Return a header for a week as a table row.
  340. """
  341. s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
  342. return '<tr>%s</tr>' % s
  343. def formatmonthname(self, theyear, themonth, withyear=True):
  344. """
  345. Return a month name as a table row.
  346. """
  347. if withyear:
  348. s = '%s %s' % (month_name[themonth], theyear)
  349. else:
  350. s = '%s' % month_name[themonth]
  351. return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  352. def formatmonth(self, theyear, themonth, withyear=True):
  353. """
  354. Return a formatted month as a table.
  355. """
  356. v = []
  357. a = v.append
  358. a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
  359. a('\n')
  360. a(self.formatmonthname(theyear, themonth, withyear=withyear))
  361. a('\n')
  362. a(self.formatweekheader())
  363. a('\n')
  364. for week in self.monthdays2calendar(theyear, themonth):
  365. a(self.formatweek(week))
  366. a('\n')
  367. a('</table>')
  368. a('\n')
  369. return ''.join(v)
  370. def formatyear(self, theyear, width=3):
  371. """
  372. Return a formatted year as a table of tables.
  373. """
  374. v = []
  375. a = v.append
  376. width = max(width, 1)
  377. a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
  378. a('\n')
  379. a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
  380. for i in range(January, January+12, width):
  381. # months in this row
  382. months = range(i, min(i+width, 13))
  383. a('<tr>')
  384. for m in months:
  385. a('<td>')
  386. a(self.formatmonth(theyear, m, withyear=False))
  387. a('</td>')
  388. a('</tr>')
  389. a('</table>')
  390. return ''.join(v)
  391. def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
  392. """
  393. Return a formatted year as a complete HTML page.
  394. """
  395. if encoding is None:
  396. encoding = sys.getdefaultencoding()
  397. v = []
  398. a = v.append
  399. a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
  400. a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
  401. a('<html>\n')
  402. a('<head>\n')
  403. a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
  404. if css is not None:
  405. a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
  406. a('<title>Calendar for %d</title>\n' % theyear)
  407. a('</head>\n')
  408. a('<body>\n')
  409. a(self.formatyear(theyear, width))
  410. a('</body>\n')
  411. a('</html>\n')
  412. return ''.join(v).encode(encoding, "xmlcharrefreplace")
  413. class different_locale:
  414. def __init__(self, locale):
  415. self.locale = locale
  416. def __enter__(self):
  417. self.oldlocale = _locale.getlocale(_locale.LC_TIME)
  418. _locale.setlocale(_locale.LC_TIME, self.locale)
  419. def __exit__(self, *args):
  420. _locale.setlocale(_locale.LC_TIME, self.oldlocale)
  421. class LocaleTextCalendar(TextCalendar):
  422. """
  423. This class can be passed a locale name in the constructor and will return
  424. month and weekday names in the specified locale. If this locale includes
  425. an encoding all strings containing month and weekday names will be returned
  426. as unicode.
  427. """
  428. def __init__(self, firstweekday=0, locale=None):
  429. TextCalendar.__init__(self, firstweekday)
  430. if locale is None:
  431. locale = _locale.getdefaultlocale()
  432. self.locale = locale
  433. def formatweekday(self, day, width):
  434. with different_locale(self.locale):
  435. if width >= 9:
  436. names = day_name
  437. else:
  438. names = day_abbr
  439. name = names[day]
  440. return name[:width].center(width)
  441. def formatmonthname(self, theyear, themonth, width, withyear=True):
  442. with different_locale(self.locale):
  443. s = month_name[themonth]
  444. if withyear:
  445. s = "%s %r" % (s, theyear)
  446. return s.center(width)
  447. class LocaleHTMLCalendar(HTMLCalendar):
  448. """
  449. This class can be passed a locale name in the constructor and will return
  450. month and weekday names in the specified locale. If this locale includes
  451. an encoding all strings containing month and weekday names will be returned
  452. as unicode.
  453. """
  454. def __init__(self, firstweekday=0, locale=None):
  455. HTMLCalendar.__init__(self, firstweekday)
  456. if locale is None:
  457. locale = _locale.getdefaultlocale()
  458. self.locale = locale
  459. def formatweekday(self, day):
  460. with different_locale(self.locale):
  461. s = day_abbr[day]
  462. return '<th class="%s">%s</th>' % (self.cssclasses[day], s)
  463. def formatmonthname(self, theyear, themonth, withyear=True):
  464. with different_locale(self.locale):
  465. s = month_name[themonth]
  466. if withyear:
  467. s = '%s %s' % (s, theyear)
  468. return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  469. # Support for old module level interface
  470. c = TextCalendar()
  471. firstweekday = c.getfirstweekday
  472. def setfirstweekday(firstweekday):
  473. if not MONDAY <= firstweekday <= SUNDAY:
  474. raise IllegalWeekdayError(firstweekday)
  475. c.firstweekday = firstweekday
  476. monthcalendar = c.monthdayscalendar
  477. prweek = c.prweek
  478. week = c.formatweek
  479. weekheader = c.formatweekheader
  480. prmonth = c.prmonth
  481. month = c.formatmonth
  482. calendar = c.formatyear
  483. prcal = c.pryear
  484. # Spacing of month columns for multi-column year calendar
  485. _colwidth = 7*3 - 1 # Amount printed by prweek()
  486. _spacing = 6 # Number of spaces between columns
  487. def format(cols, colwidth=_colwidth, spacing=_spacing):
  488. """Prints multi-column formatting for year calendars"""
  489. print(formatstring(cols, colwidth, spacing))
  490. def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
  491. """Returns a string formatted from n strings, centered within n columns."""
  492. spacing *= ' '
  493. return spacing.join(c.center(colwidth) for c in cols)
  494. EPOCH = 1970
  495. _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
  496. def timegm(tuple):
  497. """Unrelated but handy function to calculate Unix timestamp from GMT."""
  498. year, month, day, hour, minute, second = tuple[:6]
  499. days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
  500. hours = days*24 + hour
  501. minutes = hours*60 + minute
  502. seconds = minutes*60 + second
  503. return seconds
  504. def main(args):
  505. import optparse
  506. parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]")
  507. parser.add_option(
  508. "-w", "--width",
  509. dest="width", type="int", default=2,
  510. help="width of date column (default 2, text only)"
  511. )
  512. parser.add_option(
  513. "-l", "--lines",
  514. dest="lines", type="int", default=1,
  515. help="number of lines for each week (default 1, text only)"
  516. )
  517. parser.add_option(
  518. "-s", "--spacing",
  519. dest="spacing", type="int", default=6,
  520. help="spacing between months (default 6, text only)"
  521. )
  522. parser.add_option(
  523. "-m", "--months",
  524. dest="months", type="int", default=3,
  525. help="months per row (default 3, text only)"
  526. )
  527. parser.add_option(
  528. "-c", "--css",
  529. dest="css", default="calendar.css",
  530. help="CSS to use for page (html only)"
  531. )
  532. parser.add_option(
  533. "-L", "--locale",
  534. dest="locale", default=None,
  535. help="locale to be used from month and weekday names"
  536. )
  537. parser.add_option(
  538. "-e", "--encoding",
  539. dest="encoding", default=None,
  540. help="Encoding to use for output."
  541. )
  542. parser.add_option(
  543. "-t", "--type",
  544. dest="type", default="text",
  545. choices=("text", "html"),
  546. help="output type (text or html)"
  547. )
  548. (options, args) = parser.parse_args(args)
  549. if options.locale and not options.encoding:
  550. parser.error("if --locale is specified --encoding is required")
  551. sys.exit(1)
  552. locale = options.locale, options.encoding
  553. if options.type == "html":
  554. if options.locale:
  555. cal = LocaleHTMLCalendar(locale=locale)
  556. else:
  557. cal = HTMLCalendar()
  558. encoding = options.encoding
  559. if encoding is None:
  560. encoding = sys.getdefaultencoding()
  561. optdict = dict(encoding=encoding, css=options.css)
  562. write = sys.stdout.buffer.write
  563. if len(args) == 1:
  564. write(cal.formatyearpage(datetime.date.today().year, **optdict))
  565. elif len(args) == 2:
  566. write(cal.formatyearpage(int(args[1]), **optdict))
  567. else:
  568. parser.error("incorrect number of arguments")
  569. sys.exit(1)
  570. else:
  571. if options.locale:
  572. cal = LocaleTextCalendar(locale=locale)
  573. else:
  574. cal = TextCalendar()
  575. optdict = dict(w=options.width, l=options.lines)
  576. if len(args) != 3:
  577. optdict["c"] = options.spacing
  578. optdict["m"] = options.months
  579. if len(args) == 1:
  580. result = cal.formatyear(datetime.date.today().year, **optdict)
  581. elif len(args) == 2:
  582. result = cal.formatyear(int(args[1]), **optdict)
  583. elif len(args) == 3:
  584. result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
  585. else:
  586. parser.error("incorrect number of arguments")
  587. sys.exit(1)
  588. write = sys.stdout.write
  589. if options.encoding:
  590. result = result.encode(options.encoding)
  591. write = sys.stdout.buffer.write
  592. write(result)
  593. if __name__ == "__main__":
  594. main(sys.argv)