Ticket #4449: profile_gettext.py

File profile_gettext.py, 2.4 KB (added by manuq, 11 years ago)
Line 
1import sys
2import gettext
3import subprocess
4
5
6def get_locale_name_gettext(code, language_name, country_name,
7                            lang_iso='iso_639'):
8    language, country = code.split('_')
9
10    language_translation = None
11    try:
12        translation = gettext.translation(lang_iso, languages=[language])
13        language_translation = translation.ugettext(language_name)
14    except IOError:
15        sys.stderr.write("ugettext raised IOError for %s using %s\n" % (code, lang_iso))
16        language_translation = "Unknown"
17    except UnicodeError:
18        sys.stderr.write("ugettext raised UnicodeError for %s\n" % code)
19        language_translation = "Unknown"
20
21    country_translation = None
22    try:
23        translation = gettext.translation('iso_3166', languages=[language])
24        country_translation = translation.ugettext(country_name)
25    except IOError:
26        sys.stderr.write("ugettext raised IOError for %s using %s\n" % (code, lang_iso))
27        country_translation = "Unknown"
28    except UnicodeError:
29        sys.stderr.write("ugettext raised UnicodeError for %s\n" % code)
30        country_translation = "Unknown"
31
32    return "%s (%s)" % (language_translation, country_translation)
33
34def read_all_languages():
35    fdp = subprocess.Popen(['locale', '-av'], stdout=subprocess.PIPE)
36    lines = fdp.stdout.read().split('\n')
37    locales = []
38
39    for line in lines:
40        if line.find('locale:') != -1:
41            locale = line.split()[1]
42        elif line.find('language |') != -1:
43            lang = line.lstrip('language |')
44        elif line.find('territory |') != -1:
45            territory = line.lstrip('territory |')
46            if locale.endswith('utf8') and len(lang):
47                locales.append((lang, territory, locale))
48
49    #FIXME: This is a temporary workaround for locales that are essential to
50    # OLPC, but are not in Glibc yet.
51    locales.append(('Kreyol', 'Haiti', 'ht_HT.utf8'))
52    locales.append(('Dari', 'Afghanistan', 'fa_AF.utf8'))
53    locales.append(('Pashto', 'Afghanistan', 'ps_AF.utf8'))
54
55    locales.sort()
56    return locales
57
58if __name__ == '__main__':
59    available_locales = read_all_languages()
60
61    names_gettext_iso_639 = {}
62    for language, country, code in available_locales:
63        locale_name = get_locale_name_gettext(code, language, country,
64                                              lang_iso='iso_639')
65        names_gettext_iso_639[code] = locale_name