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