calendar.py 24 KB

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