Python localization made easy

Python
Here’s a set of simple steps to localize a Python application for different translations. This tutorial provides a clear set of steps with sample code.

Step 1: Initialize your application

Here is the code to initialize your application with localization enabled:


If you can’t see the source code try here.

This snippet looks for a resource file based on the users locale. For instance, “res/messages_en.mo” for English. If it fails to open the appropriate translation file, it falls back to NullTranslations, which simply performs no translation.

Step 2: Prepare your application for translation

trans.install() generates a global function available to all modules in your application: _().

Find all the strings in your application that you wish to translate, and wrap them with the _() function.

i.e. “Hello” becomes _(“Hello”).

This applies to parameterized strings as well. e.g. “Hello %s” % name becomes _(“Hello %s”) % name.

Step 3: Generate the pot

That’s messages.pot.

Run the command xgettext *.py or pygettext *.py. Under Windows, you might have to look for this tool. Under the Python installation directory, try Tools/i18n.

This command looks for all strings inside the _() function, and generates the file messages.pot.

Step 4: Translate

Send your generated pot file to your translator. They will replace the empty strings with the appropriate translations and return the file to you.

Step 5: Generate the mo

Save the returned file to reflect the new language that your application has been translated to. e.g. messages_De.po

Run the command msgfmt -o res/messages_De.mo messages_De.po to generate the required .mo file.

As with pygettext, if your system doesn’t find this command, look in Tools/i18n under the Python installation directory.

After running this command, the translation file required by the application will be in the res directory. When you’re distributing the application, make sure the res directory goes too.

Step 6: Test

On Windows XP, you can change your locale with the following steps:

  • Start->Control Panel->Regional and Language Options;
  • Under “Regional Options”, choose the locale for the translation file you have created and click “Apply”;
  • Start the Python application;
  • (Hopefully) enjoy your translated application!

In summary…

It’s straightforward to setup localization with Python once you know how.

Leave a Reply