gettext: FileNotFoundError: [Errno 2] No translation file found for domain: 'base'

Question:

It seems that I am unable to get my GNU gettext utility to work properly, despite closely following both documentation and online resources.

My folder structure is the following:

/
|- src
|    |- __init__.py
|    |- main.py
|- locales
     |- ru
          |- LC_MESSAGES
               |- base.mo
               |- base.po

the top of my main.py reads like this (Windows machine):

import argparse
import gettext
from gettext import gettext as _

argparser = argparse.ArgumentParser()
argparser.add_argument("--language", required=False, default="en")
arguments = argparser.parse_args()
gettext.translation(
    "base", localedir=r".locales", languages=[arguments.language[:2]]
).install()

And yet, when I try to run the script in either English or Russian, I still get an error:

FileNotFoundError: [Errno 2] No translation file found for domain: 'base'

What am I doing wrong?

I’ve tried putting locales dir inside the src folder and dropping the dot prefix (gettext.translation("base", localedir=r"locales", ...), but it doesn’t seem to have changed anything.

EDIT: adding fallback=True seems to have worked, but translation does not seem to process. You can find details to reproduce here.

Answers:

I’ve managed to solve my problem by doing the combination of the following, not sure which exact thing has helped:

  1. Specifying the absolute path with pathlib.Path(__file__).resolve().parents[1] / "locale" instead of a simple string with a dot.

  2. Not overwriting the underscore after install – from gettext import gettext as _ has to be removed, and to silence the PyCharm linter I use this trick:

from gettext import gettext as _

def main() -> None:
    gettext.translation(...).install()
    del globals()["_"]  # Keep PyCharm happy
  1. Locale has to be a list – [ru], not ru.
Answered By: Vladimir Vilimaitis
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.