views:

56

answers:

1

I'm cleaning up some localisation and translation settings in our PyGTK application. The app is only intended to be used under GNU/Linux systems. One of the features we want is for users to select the language used for the applications (some prefer their native language, some prefer English for consistency, some like French because it sounds romantic, etc).

For this to work, I need to actually show a combo box with the various languages available. How can I get this list? In fact, I need a list of pairs of the language code ("en", "ru", etc) and the language name in the native language ("English (US)", "Русские").

If I had to implement a brute force method, I'd do something like: look in the system locale dir (eg. "/usr/share/locale") for all language code dirs (eg. "en/") containing the relative path "LC_MESSAGES/OurAppName.mo".

Is there a more programmatic way?

+1  A: 

You can use gettext to find whether a translation is available and installed, but you need babel (which was available on my Ubuntu system as the package python-pybabel) to get the names. Here is a code snippet which returns the list that 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

To change languages in the middle of your program, see the relevant section of the Python docs. This probably entails reconstructing all your GTK widgets, although I'm not sure.

For more information on gettext.find, here is the link to that too.

ptomato
I was not aware of the `gettext.find(...)` method, OR the babel package — neat! I'll try this out soon.
detly
Are there decent docs for pybabel, by the way?
detly
Fairly decent, but not online -- they're installed with the package.
ptomato