Gettext and changing translations on the fly

Gettext basics:

  • Extracting translatable strings:
    xgettext --language=Python --keyword=_ --output=app.pot

  • Creating a new translation:
    msginit --input=app.pot --locale=en_CA
    Translate the msgstr inside the new file.

  • Generate the .mo file (which is used by gettext):
    msgfmt --output-file=en_CA/LC_MESSAGES/ en_CA.po

Information extracted from this page.

Using gettext inside Python (and changing language on the fly):

import gettext
import os

gettext.bindtextdomain('app', 'langs')
_ = gettext.gettext

os.environ['LANG'] = 'en'
print _('Translated message')

os.environ['LANG'] = 'pt_BR'
print _('Translated message')