gettext --- 多語言國際化服務¶
原始碼:Lib/gettext.py
The gettext module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
GNU gettext message catalog API and a higher level, class-based API that may
be more appropriate for Python files. The interface described below allows you
to write your module and application messages in one natural language, and
provide a catalog of translated messages for running under different natural
languages.
Some hints on localizing your Python modules and applications are also given.
GNU gettext API¶
The gettext module defines the following API, which is very similar to
the GNU gettext 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.
- gettext.bindtextdomain(domain, localedir=None)¶
Bind the domain to the locale directory localedir. More concretely,
gettextwill look for binary.mofiles for the given domain using the path (on Unix):localedir/language/LC_MESSAGES/domain.mo, where language is searched for in the environment variablesLANGUAGE,LC_ALL,LC_MESSAGES, andLANGrespectively.If localedir is omitted or
None, then the current binding for domain is returned. [1]
- gettext.textdomain(domain=None)¶
Change or query the current global domain. If domain is
None, then the current global domain is returned, otherwise the global domain is set to domain, which is returned.
- gettext.gettext(message)¶
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as
_()in the local namespace (see examples below).
- gettext.ngettext(singular, plural, n)¶
Like
gettext(), but consider plural forms. If a translation is found, apply the plural formula to n, and return the resulting message (some languages have more than two plural forms). If no translation is found, return singular if n is 1; return plural otherwise.The Plural formula is taken from the catalog header. It is a C or Python expression that has a free variable n; the expression evaluates to the index of the plural in the catalog. See the GNU gettext documentation for the precise syntax to be used in
.pofiles and the formulas for a variety of languages.
- gettext.dngettext(domain, singular, plural, n)¶
Like
ngettext(), but look the message up in the specified domain.
- gettext.pgettext(context, message)¶
- gettext.dpgettext(domain, context, message)¶
- gettext.npgettext(context, singular, plural, n)¶
- gettext.dnpgettext(domain, context, singular, plural, n)¶
Similar to the corresponding functions without the
pin the prefix (that is,gettext(),dgettext(),ngettext(),dngettext()), but the translation is restricted to the given message context.在 3.8 版被加入.
Note that GNU gettext also defines a dcgettext() method, but
this was deemed not useful and so it is currently unimplemented.
Here's an example of typical usage for this API:
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print(_('This is a translatable string.'))
Class-based API¶
The class-based API of the gettext module gives you more flexibility and
greater convenience than the GNU gettext API. It is the recommended
way of localizing your Python applications and modules. gettext defines
a GNUTranslations class which implements the parsing of GNU .mo format
files, and has methods for returning strings. Instances of this class can also
install themselves in the built-in namespace as the function _().
- gettext.find(domain, localedir=None, languages=None, all=False)¶
This function implements the standard
.mofile search algorithm. It takes a domain, identical to whattextdomain()takes. Optional localedir is as inbindtextdomain(). Optional languages is a list of strings, where each string is a language code.If localedir is not given, then the default system locale directory is used. [2] If languages is not given, then the following environment variables are searched:
LANGUAGE,LC_ALL,LC_MESSAGES, andLANG. The first one returning a non-empty value is used for the languages variable. The environment variables should contain a colon separated list of languages, which will be split on the colon to produce the expected list of language code strings.find()then expands and normalizes the languages, and then iterates through them, searching for an existing file built of these components:localedir/language/LC_MESSAGES/domain.moThe first such file name that exists is returned by
find(). If no such file is found, thenNoneis returned. If all is given, it returns a list of all file names, in the order in which they appear in the languages list or the environment variables.
- gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False)¶
Return a
*Translationsinstance based on the domain, localedir, and languages, which are first passed tofind()to get a list of the associated.mofile paths. Instances with identical.mofile names are cached. The actual class instantiated is class_ if provided, otherwiseGNUTranslations. The class's constructor must take a single file object argument.If multiple files are found, later files are used as fallbacks for earlier ones. To allow setting the fallback,
copy.copy()is used to clone each translation object from the cache; the actual instance data is still shared with the cache.If no
.mofile is found, this function raisesOSErrorif fallback is false (which is the default), and returns aNullTranslationsinstance if fallback is true.在 3.11 版的變更: codeset 參數被移除。
- gettext.install(domain, localedir=None, *, names=None)¶
This installs the function
_()in Python's builtins namespace, based on domain and localedir which are passed to the functiontranslation().For the names parameter, please see the description of the translation object's
install()method.As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the
_()function, like this:print(_('This string will be translated.'))
For convenience, you want the
_()function to be installed in Python's builtins namespace, so it is easily accessible in all modules of your application.在 3.11 版的變更: names is now a keyword-only parameter.
The NullTranslations class¶
Translation classes are what actually implement the translation of original
source file message strings to translated message strings. The base class used
by all translation classes is NullTranslations; this provides the basic
interface you can use to write your own specialized translation classes. Here
are the methods of NullTranslations:
- class gettext.NullTranslations(fp=None)¶
Takes an optional file object fp, which is ignored by the base class. Initializes "protected" instance variables _info and _charset which are set by derived classes, as well as _fallback, which is set through
add_fallback(). It then callsself._parse(fp)if fp is notNone.- _parse(fp)¶
No-op in the base class, this method takes file object fp, and reads the data from the file, initializing its message catalog. If you have an unsupported message catalog file format, you should override this method to parse your format.
- add_fallback(fallback)¶
Add fallback as the fallback object for the current translation object. A translation object should consult the fallback if it cannot provide a translation for a given message.
- gettext(message)¶
If a fallback has been set, forward
gettext()to the fallback. Otherwise, return message. Overridden in derived classes.
- ngettext(singular, plural, n)¶
If a fallback has been set, forward
ngettext()to the fallback. Otherwise, return singular if n is 1; return plural otherwise. Overridden in derived classes.
- pgettext(context, message)¶
If a fallback has been set, forward
pgettext()to the fallback. Otherwise, return the translated message. Overridden in derived classes.在 3.8 版被加入.
- npgettext(context, singular, plural, n)¶
If a fallback has been set, forward
npgettext()to the fallback. Otherwise, return the translated message. Overridden in derived classes.在 3.8 版被加入.
- info()¶
Return a dictionary containing the metadata found in the message catalog file.
- charset()¶
Return the encoding of the message catalog file.
- install(names=None)¶
This method installs
gettext()into the built-in namespace, binding it to_.If the names parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in addition to
_(). Supported names are'gettext','ngettext','pgettext', and'npgettext'.Note that this is only one way, albeit the most convenient way, to make the
_()function available to your application. Because it affects the entire application globally, and specifically the built-in namespace, localized modules should never install_(). Instead, they should use this code to make