Python gettext.translation() Examples

The following are 30 code examples of gettext.translation(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gettext , or try the search function .
Example #1
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def resource_exists(name):
    """Return true if the given resource exists"""
    try:
        open_resource(name).close()
        return True
    except IOError:
        return False


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #2
Source File: __init__.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def __resource_exists(name):
    """Return true if the given resource exists"""
    try:
        open_resource(name).close()
        return True
    except IOError:
        return False


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
# 
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #3
Source File: math2html.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def findtranslation(self):
    "Find the translation for the document language."
    self.langcodes = None
    if not DocumentParameters.language:
      Trace.error('No language in document')
      return
    if not DocumentParameters.language in TranslationConfig.languages:
      Trace.error('Unknown language ' + DocumentParameters.language)
      return
    if TranslationConfig.languages[DocumentParameters.language] == 'en':
      return
    langcodes = [TranslationConfig.languages[DocumentParameters.language]]
    try:
      self.translation = gettext.translation('elyxer', None, langcodes)
    except IOError:
      Trace.error('No translation for ' + unicode(langcodes)) 
Example #4
Source File: trans_real.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _new_gnu_trans(self, localedir, use_null_fallback=True):
        """
        Returns a mergeable gettext.GNUTranslations instance.

        A convenience wrapper. By default gettext uses 'fallback=False'.
        Using param `use_null_fallback` to avoid confusion with any other
        references to 'fallback'.
        """
        translation = gettext_module.translation(
            domain='django',
            localedir=localedir,
            languages=[self.__locale],
            codeset='utf-8',
            fallback=use_null_fallback)
        if not hasattr(translation, '_catalog'):
            # provides merge support for NullTranslations()
            translation._catalog = {}
            translation._info = {}
            translation.plural = lambda n: int(n != 1)
        return translation 
Example #5
Source File: __init__.py    From script.tvguide.fullscreen with GNU General Public License v2.0 6 votes vote down vote up
def resource_exists(name):
    """Return true if the given resource exists"""
    try:
        open_resource(name).close()
        return True
    except IOError:
        return False


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
# 
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #6
Source File: trans_real.py    From bioforum with MIT License 6 votes vote down vote up
def gettext(message):
    """
    Translate the 'message' string. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')

    if len(eol_message) == 0:
        # Return an empty value of the corresponding type if an empty message
        # is given, instead of metadata, which is the default gettext behavior.
        result = type(message)("")
    else:
        _default = _default or translation(settings.LANGUAGE_CODE)
        translation_object = getattr(_active, "value", _default)

        result = translation_object.gettext(eol_message)

    if isinstance(message, SafeData):
        return mark_safe(result)

    return result 
Example #7
Source File: i18n.py    From jbox with MIT License 6 votes vote down vote up
def get_translations(languages=None, getter=get_builtin_gnu_translations):
    """
    Get a WTForms translation object which wraps a low-level translations object.

    :param languages:
        A sequence of languages to try, in order.
    :param getter:
        A single-argument callable which returns a low-level translations object.
    """
    translations = getter(languages)

    if hasattr(translations, 'ugettext'):
        return DefaultTranslations(translations)
    else:
        # Python 3 has no ugettext/ungettext, so just return the translations object.
        return translations 
Example #8
Source File: test_gettext.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_the_alternative_interface(self):
        eq = self.assertEqual
        # test the alternative interface
        with open(self.mofile, 'rb') as fp:
            t = gettext.GNUTranslations(fp)
        # Install the translation object
        t.install()
        eq(_('nudge nudge'), 'wink wink')
        # Try unicode return type
        t.install(unicode=True)
        eq(_('mullusk'), 'bacon')
        # Test installation of other methods
        import __builtin__
        t.install(unicode=True, names=["gettext", "lgettext"])
        eq(_, t.ugettext)
        eq(__builtin__.gettext, t.ugettext)
        eq(lgettext, t.lgettext)
        del __builtin__.gettext
        del __builtin__.lgettext 
Example #9
Source File: test_gettext.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_cache(self):
        self.localedir = os.curdir
        self.mofile = MOFILE

        self.assertEqual(len(gettext._translations), 0)

        t = gettext.translation('gettext', self.localedir)

        self.assertEqual(len(gettext._translations), 1)

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations)

        # Calling it again doesn't add to the cache

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations) 
Example #10
Source File: language.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def configure(self, lang=None):
        """
        Configures the funcion "_" for translating the texts of Wapiti,
        this method loads the language indicated as parameter or if the
        parameter is not specified, it will take the default language
        of the operating system.
        """
        if lang is None:
            # if lang is not specified, default language is used
            defLocale = locale.getdefaultlocale()
            langCounty = defLocale[0]   # en_UK
            lang = langCounty[:2]  # en
        if lang not in self.AVAILABLE_LANGS:
            # if lang is not one of the supported languages, we use english
            print("Oups! No translations found for your language... Using english.")
            print("Please send your translations for improvements.")
            print("===============================================================")
            lang = 'en'
        lan = gettext.translation('wapiti',
                                  self.LANG_PATH,
                                  languages=[lang],
                                  codeset="UTF-8")
        lan.install(unicode=1)

        #funcion which translates
        def _(key):
            return lan.lgettext(key) 
Example #11
Source File: test_gettext.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_the_alternative_interface(self):
        eq = self.assertEqual
        # test the alternative interface
        with open(self.mofile, 'rb') as fp:
            t = gettext.GNUTranslations(fp)
        # Install the translation object
        t.install()
        eq(_('nudge nudge'), 'wink wink')
        # Try unicode return type
        t.install(unicode=True)
        eq(_('mullusk'), 'bacon')
        # Test installation of other methods
        import __builtin__
        t.install(unicode=True, names=["gettext", "lgettext"])
        eq(_, t.ugettext)
        eq(__builtin__.gettext, t.ugettext)
        eq(lgettext, t.lgettext)
        del __builtin__.gettext
        del __builtin__.lgettext 
Example #12
Source File: test_gettext.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_cache(self):
        self.localedir = os.curdir
        self.mofile = MOFILE

        self.assertEqual(len(gettext._translations), 0)

        t = gettext.translation('gettext', self.localedir)

        self.assertEqual(len(gettext._translations), 1)

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations)

        # Calling it again doesn't add to the cache

        t = gettext.translation('gettext', self.localedir,
                                class_=DummyGNUTranslations)

        self.assertEqual(len(gettext._translations), 2)
        self.assertEqual(t.__class__, DummyGNUTranslations) 
Example #13
Source File: _message.py    From oslo.i18n with Apache License 2.0 6 votes vote down vote up
def _sanitize_mod_params(self, other):
        """Sanitize the object being modded with this Message.

        - Add support for modding 'None' so translation supports it
        - Trim the modded object, which can be a large dictionary, to only
        those keys that would actually be used in a translation
        - Snapshot the object being modded, in case the message is
        translated, it will be used as it was when the Message was created
        """
        if other is None:
            params = (other,)
        elif isinstance(other, dict):
            # Merge the dictionaries
            # Copy each item in case one does not support deep copy.
            params = {}
            if isinstance(self.params, dict):
                params.update((key, self._copy_param(val))
                              for key, val in self.params.items())
            params.update((key, self._copy_param(val))
                          for key, val in other.items())
        else:
            params = self._copy_param(other)
        return params 
Example #14
Source File: __init__.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def resource_exists(name):
    return loader.resource_exists(name)


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #15
Source File: __init__.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def resource_exists(name):
    """Return true if the given resource exists"""
    try:
        open_resource(name).close()
        return True
    except IOError:
        return False


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #16
Source File: i18n.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def get_translations(languages=None, getter=get_builtin_gnu_translations):
    """
    Get a WTForms translation object which wraps a low-level translations object.

    :param languages:
        A sequence of languages to try, in order.
    :param getter:
        A single-argument callable which returns a low-level translations object.
    """
    translations = getter(languages)

    if hasattr(translations, 'ugettext'):
        return DefaultTranslations(translations)
    else:
        # Python 3 has no ugettext/ungettext, so just return the translations object.
        return translations 
Example #17
Source File: _message.py    From oslo.i18n with Apache License 2.0 6 votes vote down vote up
def __new__(cls, msgid, msgtext=None, params=None,
                domain='oslo', has_contextual_form=False,
                has_plural_form=False, *args):
        """Create a new Message object.

        In order for translation to work gettext requires a message ID, this
        msgid will be used as the base unicode text. It is also possible
        for the msgid and the base unicode text to be different by passing
        the msgtext parameter.
        """
        # If the base msgtext is not given, we use the default translation
        # of the msgid (which is in English) just in case the system locale is
        # not English, so that the base text will be in that locale by default.
        if not msgtext:
            msgtext = Message._translate_msgid(msgid, domain)
        # We want to initialize the parent unicode with the actual object that
        # would have been plain unicode if 'Message' was not enabled.
        msg = super(Message, cls).__new__(cls, msgtext)
        msg.msgid = msgid
        msg.domain = domain
        msg.params = params
        msg.has_contextual_form = has_contextual_form
        msg.has_plural_form = has_plural_form
        return msg 
Example #18
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def resource_exists(name):
    """Return true if the given resource exists"""
    try:
        open_resource(name).close()
        return True
    except IOError:
        return False


# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
#         'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
#         fallback=True
#         )
# def _(timezone_name):
#     """Translate a timezone name using the current locale, returning Unicode"""
#     return t.ugettext(timezone_name) 
Example #19
Source File: fakes.py    From oslo.i18n with Apache License 2.0 6 votes vote down vote up
def translator(locales_map):
        """Build mock translator for the given locales.

        Returns a mock gettext.translation function that uses
        individual TestTranslations to translate in the given locales.

        :param locales_map: A map from locale name to a translations map.
                            {
                             'es': {'Hi': 'Hola', 'Bye': 'Adios'},
                             'zh': {'Hi': 'Ni Hao', 'Bye': 'Zaijian'}
                            }


        """
        def _translation(domain, localedir=None,
                         languages=None, fallback=None):
            if languages:
                language = languages[0]
                if language in locales_map:
                    return FakeTranslations(locales_map[language])
            return gettext.NullTranslations()
        return _translation 
Example #20
Source File: math2html.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def findtranslation(self):
    "Find the translation for the document language."
    self.langcodes = None
    if not DocumentParameters.language:
      Trace.error('No language in document')
      return
    if not DocumentParameters.language in TranslationConfig.languages:
      Trace.error('Unknown language ' + DocumentParameters.language)
      return
    if TranslationConfig.languages[DocumentParameters.language] == 'en':
      return
    langcodes = [TranslationConfig.languages[DocumentParameters.language]]
    try:
      self.translation = gettext.translation('elyxer', None, langcodes)
    except IOError:
      Trace.error('No translation for ' + str(langcodes)) 
Example #21
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def ngettext(singular, plural, number):
    """
    Return a string of the translation of either the singular or plural,
    based on the number.
    """
    return do_ntranslate(singular, plural, number, 'ngettext') 
Example #22
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def _add_installed_apps_translations(self):
        """Merge translations from each installed app."""
        try:
            app_configs = reversed(list(apps.get_app_configs()))
        except AppRegistryNotReady:
            raise AppRegistryNotReady(
                "The translation infrastructure cannot be initialized before the "
                "apps registry is ready. Check that you don't make non-lazy "
                "gettext calls at import time.")
        for app_config in app_configs:
            localedir = os.path.join(app_config.path, 'locale')
            if os.path.exists(localedir):
                translation = self._new_gnu_trans(localedir)
                self.merge(translation) 
Example #23
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def _init_translation_catalog(self):
        """Create a base catalog using global django translations."""
        settingsfile = sys.modules[settings.__module__].__file__
        localedir = os.path.join(os.path.dirname(settingsfile), 'locale')
        translation = self._new_gnu_trans(localedir)
        self.merge(translation) 
Example #24
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def _new_gnu_trans(self, localedir, use_null_fallback=True):
        """
        Return a mergeable gettext.GNUTranslations instance.

        A convenience wrapper. By default gettext uses 'fallback=False'.
        Using param `use_null_fallback` to avoid confusion with any other
        references to 'fallback'.
        """
        return gettext_module.translation(
            domain=self.domain,
            localedir=localedir,
            languages=[self.__locale],
            codeset='utf-8',
            fallback=use_null_fallback) 
Example #25
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, language, domain=None, localedirs=None):
        """Create a GNUTranslations() using many locale directories"""
        gettext_module.GNUTranslations.__init__(self)
        if domain is not None:
            self.domain = domain

        self.__language = language
        self.__to_language = to_language(language)
        self.__locale = to_locale(language)
        self._catalog = None
        # If a language doesn't have a catalog, use the Germanic default for
        # pluralization: anything except one is pluralized.
        self.plural = lambda n: int(n != 1)

        if self.domain == 'django':
            if localedirs is not None:
                # A module-level cache is used for caching 'django' translations
                warnings.warn("localedirs is ignored when domain is 'django'.", RuntimeWarning)
                localedirs = None
            self._init_translation_catalog()

        if localedirs:
            for localedir in localedirs:
                translation = self._new_gnu_trans(localedir)
                self.merge(translation)
        else:
            self._add_installed_apps_translations()

        self._add_local_translations()
        if self.__language == settings.LANGUAGE_CODE and self.domain == 'django' and self._catalog is None:
            # default lang should have at least one translation file available.
            raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE)
        self._add_fallback(localedirs)
        if self._catalog is None:
            # No catalogs found for this language, set an empty catalog.
            self._catalog = {} 
Example #26
Source File: trans_real.py    From bioforum with MIT License 5 votes vote down vote up
def deactivate_all():
    """
    Make the active translation object a NullTranslations() instance. This is
    useful when we want delayed translations to appear as the original string
    for some reason.
    """
    _active.value = gettext_module.NullTranslations()
    _active.value.to_language = lambda *args: None 
Example #27
Source File: jailedgrader.py    From xqueue-watcher with GNU Affero General Public License v3.0 5 votes vote down vote up
def _enable_i18n(self, language):
        trans = gettext.translation('graders', localedir=self.locale_dir, fallback=True, languages=[language])
        trans.install(names=None) 
Example #28
Source File: math2html.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def getmessage(self, key):
    "Get the translated message for the given key."
    if self.first:
      self.findtranslation()
      self.first = False
    message = self.getuntranslated(key)
    if not self.translation:
      return message
    try:
      message = self.translation.ugettext(message)
    except IOError:
      pass
    return message 
Example #29
Source File: math2html.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
    self.translation = None
    self.first = True 
Example #30
Source File: math2html.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def getmessage(self, key):
    "Get the translated message for the given key."
    if self.first:
      self.findtranslation()
      self.first = False
    message = self.getuntranslated(key)
    if not self.translation:
      return message
    try:
      message = self.translation.ugettext(message)
    except IOError:
      pass
    return message