向 gettext 询问 Python 中的当前语言和翻译源

Ask gettext about current language and translation source in Python

我在python3中像这样初始化gettext非常简单。

>>> import gettext
>>> gettext.install('i18n-test', 'locales')
>>> print(_('Hello World!'))
Hallo Welt!

我可以问 gettext 它当前使用哪种语言(不能是系统默认语言 LANGUAGE!)以及它从哪里打开 .mo 文件?

我在 API 中看不到这样的东西。

来自文档;

If you use this API you will affect the translation of your entire application globally. Often this is what you want if your application is monolingual, with the choice of language dependent on the locale of your user. If you are localizing a Python module, or if your application needs to switch languages on the fly, you probably want to use the class-based API instead.

所以您最好使用 Class-based API 来执行此操作。祝你好运!

gettext模块的find功能正是你所需要的。更确切地说,它由 install 函数内部使用,因此它将 return install 将使用的内容:

gettext.install(domain, localedir=None, codeset=None, names=None)
This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation()...

然后

gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None)
Return a Translations instance based on the domain, localedir, and languages, which are first passed to find() to get a list of the associated .mo file paths...

所以你应该使用:

file = gettext.find('i18n-test', 'locales')

它应该return一个像localedir/language/LC_MESSAGES/domain.mo这样的文件名,其中language是gettext选择的语言。