ยปCore Development>Code coverage>Lib/calendar.py

Python code coverage for Lib/calendar.py

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