List of available languages ​​for PyGTK UI strings

I am clearing some localization and translation settings in our PyGTK application. The app is intended for use on GNU / Linux systems only. One of the features we want is to choose the language used for applications (some prefer their own language, some prefer English for consistency, some are similar to French because it sounds romantic, etc.).

For this to work, I need to show the box with all available languages. How can I get this list? In fact, I need a list of language code pairs ("en", "ru", etc.) and the name of the language in my native language ("English (US)", "Russian",).

If I had to implement brute force, I would do something like: look in the system locale directory (for example, "/ usr / share / locale") for all language codes of languages ​​(for example, "ru /) containing the relative path "LC_MESSAGES / OurAppName.mo".

Is there a more programmatic way?

+3
source share
2 answers

You can use gettext to find out if a translation is available and installed, but to get the names you need babel (which was available on my Ubuntu system as a package python-pybabel). Here is a snippet of code that returns the list you want:

import gettext
import babel

messagefiles = gettext.find('OurAppName', 
    languages=babel.Locale('en').languages.keys(),
    all=True)
messagefiles.sort()

languages = [path.split('/')[-3] for path in messagefiles]
langlist = zip(languages, 
    [babel.Locale.parse(lang).display_name for lang in languages])

print langlist

, . Python. , GTK, .

gettext.find, .

+2

, gettext.find, , , Babel. , babel display_name .

def available_langs(self, domain=None, localedir=None):
    if domain is None:
        domain = gettext._current_domain
    if localedir is None:
        localedir = gettext._default_localedir
    files = glob(os.path.join(localedir, '*', 'LC_MESSAGES', '%s.mo' % domain))
    langs = [file.split(os.path.sep)[-3] for file in files]
    return langs
0

Source: https://habr.com/ru/post/1746734/


All Articles