Simple console calendar #2 (raising errors, sys.argv values handling)

In the earlier >>article<< the console calendar does not use the richness of the calendar module. To simplify the code, you can use the ‘ready-made’ class TextCalendar from this module.

You can define the cal2 () function, which can be imported from the cal2 module, or called from the console. When invoked from the console, you need to give the file execute permissions (chmod + x

Running the file without any arguments, ie ./, will display the calendar for the current year and month in the console. Alternatively, we can run the program with 2 arguments: year and month. Specifying a different number of arguments will cause a TypeError.

#!/usr/bin/env python

import calendar

from datetime import datetime

import sys

def cal2(,
    Simple console calendar.
    c = calendar
    text_calendar = c.TextCalendar(c.firstweekday())
    print(text_calendar.formatmonth(year, month))

if __name__ == '__main__':
    args = sys.argv[1:]
    if len(args) == 0:
    elif len(args) == 2:
        cal2(int(args[0]), int(args[1]))
        raise TypeError(
            'cal2() takes 2 arguments ({} given)'.format(len(args)))

Instead of the TextCalendar class, we can use a child class – LocaleTextCalendar and get subtitles in accordance with the local language settings.