Skip to content

Gettext and changing translations on the fly

Gettext basics:

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

  • 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/app.mo 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.textdomain('app')
_ = gettext.gettext

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

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

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*