How to use gettext in Python for multiple languages?

79 Views Asked by At

I have a task to use the gettext library in Python to support multiple languages in my project. I've already created .po and .mo files for each supported language, and they are located in the "translations" directory.

My goal is to switch between languages based on user choice and display the corresponding texts in my application.

Here's the piece of code I've tried:

import gettext

# Make sure you have all the .po and .mo files
# Make sure all .po and .mo files are in the correct directory.

# Create a list of supported languages
supported_languages = ['ar', 'ru']

for lang in supported_languages:
    translation = gettext.translation('messages', localedir='translations', languages=[lang])
    _ = translation.gettext
    translation.install()

# Example of a shortened text for the prompt (Hello World)
SYSTEM_PROMPT_MESSAGE = _("Hello World")
print(SYSTEM_PROMPT_MESSAGE)

However, I'm facing difficulties, and the application always displays text in English, regardless of the chosen language. What am I doing wrong? How can I correctly use gettext for multiple languages in Python?

0

There are 0 best solutions below