Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: gettext doesn't load translations on Windows

This particular piece of code works very well on Linux, but not on Windows:

locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain('exposong', LOCALE_PATH)
gettext.textdomain('exposong')

Code from here

Even if i specify the locale in locale.setlocale (I tried different formats) it doesn't work. One problem might be that the locale is not set in the environment variables (but I use a German Windows version; tested on XP and Vista). If I do "Set Lang=de_DE" on the command line, everything works as expected.

Any ideas?

like image 842
Samuel Mehrbrodt Avatar asked Sep 09 '10 15:09

Samuel Mehrbrodt


2 Answers

Standard gettext module in Python does not use startdard language settings from Windows settings, but instead relies on presence one of the environment variables: LANGUAGE, LC_MESSAGES, LC_ALL or LANG. (I'd say this is example of slack porting of Unix/Linux library to Windows.)

The environment variables mentioned above do not present on typical Windows machine, because OS Windows and native applications use settings from registry instead. So you need to get the language settings from Windows registry and put them into process environment.

You can use my helper module for this: https://launchpad.net/gettext-py-windows

This helper obtains language settings from Windows settings and set LANG variable for current process, so gettext can use this settings.

So, if the application in question is not yours you can do the following. Install my gettext helper as usual with python setup.py install. Then add these lines before locale.setlocale(locale.LC_ALL, ''):

import gettext_windows
gettext_windows.setup_env()

That's all.

like image 180
bialix Avatar answered Sep 20 '22 10:09

bialix


The explanation from user bialix is correct. But instead of using another module this worked for me:

if sys.platform.startswith('win'):
    import locale
    if os.getenv('LANG') is None:
        lang, enc = locale.getdefaultlocale()
        os.environ['LANG'] = lang

That is, get the locale from the locale module and set the environment variable.

It was tested only on Windows 7, so please check it on other versions before use.

like image 31
Havok Avatar answered Sep 21 '22 10:09

Havok