Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python gettext - not translating

Sample python program: [CGI script, so it needs to select its own language rather than using whatever the host OS is set to]

import gettext
gettext.install('test', "./locale")
_ = gettext.gettext

t = gettext.translation('test', "./locale", languages=['fr'])
t.install()

print _("Hello world")

./locale/fr/LC_messages/test.mo contains the translation (as binary file, generated by running msgfmt on a .po file).

Program prints "Hello world" instead of the translated version. What could be the problem?

like image 634
OJW Avatar asked Feb 26 '11 14:02

OJW


People also ask

What is Pygettext?

pygettext uses Python's standard tokenize module to scan Python source code, generating . pot files identical to what GNU xgettext generates for C and C++ code. From there, the standard GNU tools can be used.

What is localization in Python?

Localization processWhen using gettext you identify all those strings that need to be translated and then you replace the strings with calls to gettext functions. On runtime gettext function returns the right string matching the language that is currently selected. gettext is by default included to Python platforms.


1 Answers

Maybe this answer is WAY too late, but I just found this and I think it can help you.

import gettext

t = gettext.translation('test', "./locale", languages=['fr'])
_ = t.gettext

print _("Hello world")

In my own programm, I did it this way:

import gettext

DIR = "lang"
APP = "ToolName"
gettext.textdomain(APP)
gettext.bindtextdomain(APP, DIR)
#gettext.bind_textdomain_codeset("default", 'UTF-8') # Not necessary
locale.setlocale(locale.LC_ALL, "")
LANG = "FR_fr"


lang = gettext.translation(APP, DIR, languages=[LANG], fallback = True)
_ = lang.gettext

NOTE:

My program has a lang directory on it. For every language a directory is made in lang : *XX_xx* (en_US) Inside the directory en_US there is LC_MESSAGES, and inside there is TOOLNAME.mo

But that's my way for cross-language.

like image 133
mDroidd Avatar answered Sep 20 '22 07:09

mDroidd