I18N with gettext and Python on Windows 7

The next major hurdle with J-Ben, which I have not solved yet, involves multi-language support using gettext.

In general, Python makes this easy. Python supports gettext-style string substitution via the gettext module. I’ve tested this, and it works great… on POSIX.

What about Windows?

The problem on Windows is that locale names are different than on POSIX. What would be “ja_JP” on Ubuntu would translate to “Japanese_Japan.932” on Windows.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'Japanese_Japan.932'

This won’t fly with gettext, which expects the POSIX style.

Thankfully, Python does have a way to get the user’s default locale. Windows does allow us to get locales of the same style via the WinAPI GetLocaleInfo command. This is wrapped up and transparent to Python users: all we have to do is call locale.getdefaultlocale().

>>> locale.getdefaultlocale()
('ja_JP', 'cp932')

This locale tuple has the raw data we need. It might be better to get a “locale.encoding”-type string, which the (non-public!) locale._build_localename function provides:

>>> locale._build_localename(locale.getdefaultlocale())
'ja_JP.cp932'

Since this is a non-public function, I’ll paste the source code for it since the function is not promised to be in your Python environment.

(Source: Python 2.7.1 source code, Lib/locale.py. License: Python Software Foundation License)

def _build_localename(localetuple):

    """ Builds a locale code from the given tuple (language code,
        encoding).

        No aliasing or normalizing takes place.

    """
    language, encoding = localetuple
    if language is None:
        language = 'C'
    if encoding is None:
        return language
    else:
        return language + '.' + encoding

Using one of the above methods should allow you to get a locale string which will make gettext happy. It may be as simple as setting the LC_MESSAGES environment variable if it isn’t externally set, and then maybe gettext will work. I haven’t tested this myself yet though.

(Tested with Python 2.7.1 x86 on Windows 7 Home Premium, Japanese version)

Leave a Reply

Your email address will not be published. Required fields are marked *