calendar.py 24 KB

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