pygettext examples?

Martin von Loewis loewis at informatik.hu-berlin.de
Sun Dec 2 09:17:36 EST 2001


Joseph Santaniello <joseph at arbitrary.org> writes:

> OK, so it works now (I had my directory structure incorrect) but the only 
> way I have successfully changed languages on the fly is by using 
> os.environ['LANG'] = 'no'. 

That is the way it is supposed to work: The user shall set her LANG
environment variable, and then all programs shall print messages in
the user's preferred language. If you want it differently, expect to
write more code yourself.

> I haven't been able to figure out how to use gettext.translation()
> and install() to change the language. Is there any reason why I
> shouldn't just continue to use the os.environ method?

If you want to switch languages dynamically (and ignore the user's
LANG setting altogether) I recommend that you directly load the
translation files.

the_catalog = gettext.translation("domain",languages=["no"])

def _(msg):
  return the_catalog.gettext(msg)

Then, whenever you want to switch a language, just change the_catalog.
Alternatively, you could also do

_ = gettext.translation("domain", languages=["current-lang"]).gettext

(make sure you rebind _ in a scope so that all your modules see that
change)

Notice that gettext.translation also allows specification of the
locale directory. If you don't even want to use the
LC_MESSAGES/lang.mo directory structure, you can use

the_catalog = gettext.GNUTranslation(open(mofile))

in which case control for opening the right mofile is completely in
your hands.

HTH,
Martin



More information about the Python-list mailing list