Python gettext.GNUTranslations() Examples

The following are 30 code examples of gettext.GNUTranslations(). 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: test_gettext.py    From ironpython3 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()
        eq(_('mullusk'), 'bacon')
        # Test installation of other methods
        import builtins
        t.install(names=["gettext", "lgettext"])
        eq(_, t.gettext)
        eq(builtins.gettext, t.gettext)
        eq(lgettext, t.lgettext)
        del builtins.gettext
        del builtins.lgettext 
Example #2
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 #3
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 #4
Source File: test_gettext.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_the_alternative_interface(self):
        eq = self.assertEqual
        # test the alternative interface
        fp = open(self.mofile, 'rb')
        t = gettext.GNUTranslations(fp)
        fp.close()
        # 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 #5
Source File: test_gettext.py    From oss-ftp 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 #6
Source File: test_gettext.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.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()
        eq(_('mullusk'), 'bacon')
        # Test installation of other methods
        import builtins
        t.install(names=["gettext", "lgettext"])
        eq(_, t.gettext)
        eq(builtins.gettext, t.gettext)
        eq(lgettext, t.lgettext)
        del builtins.gettext
        del builtins.lgettext 
Example #7
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 #8
Source File: test_gettext.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #9
Source File: trans_real.py    From openhgsenti with Apache License 2.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 #10
Source File: locale.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def ngettext(self, singular, plural, num):
        """
        The translation of singular/plural is returned unless the translation is
        not available and the singular contains the separator. In that case,
        the returned value is the singular.

        :param singular: The singular form of the string to be translated.
                         may contain a context seperator
        :type singular: unicode
        :param plural: The plural form of the string to be translated.
        :type plural: unicode
        :param num: the amount for which to decide the translation
        :type num: int
        :returns: Translation or the original.
        :rtype: unicode
        """
        return gettext.GNUTranslations.ngettext(self, singular, plural, num) 
Example #11
Source File: courses.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, courseid, content_description, course_fs, task_factory, hook_manager):
        """
        :param courseid: the course id
        :param content_description: a dict with all the infos of this course
        :param task_factory: a function with one argument, the task id, that returns a Task object
        """
        self._id = courseid
        self._content = content_description
        self._fs = course_fs
        self._task_factory = task_factory
        self._hook_manager = hook_manager

        self._translations = {}
        translations_fs = self._fs.from_subfolder("$i18n")
        if translations_fs.exists():
            for f in translations_fs.list(folders=False, files=True, recursive=False):
                lang = f[0:len(f) - 3]
                if translations_fs.exists(lang + ".mo"):
                    self._translations[lang] = gettext.GNUTranslations(translations_fs.get_fd(lang + ".mo"))
                else:
                    self._translations[lang] = gettext.NullTranslations() 
Example #12
Source File: test_gettext.py    From Fluid-Designer with GNU General Public License v3.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()
        eq(_('mullusk'), 'bacon')
        # Test installation of other methods
        import builtins
        t.install(names=["gettext", "lgettext"])
        eq(_, t.gettext)
        eq(builtins.gettext, t.gettext)
        eq(lgettext, t.lgettext)
        del builtins.gettext
        del builtins.lgettext 
Example #13
Source File: argument_parser.py    From mocodo with MIT License 6 votes vote down vote up
def init_localization(script_directory, language):
    if not language:
        if sys.platform.lower().startswith("darwin") and os.system("defaults read -g AppleLanguages > /tmp/languages.txt") == 0:
            language = re.search("\W*(\w+)", read_contents("/tmp/languages.txt")).group(1)
        else:
            try:
                language = locale.getdefaultlocale()[0][:2]
            except:
                language = "en"
    try:
        with open("%s/res/messages_%s.mo" % (script_directory, language), "rb") as mo_contents:
            trans = gettext.GNUTranslations(mo_contents)
    except IOError:
        trans = gettext.NullTranslations()
    
    if sys.version_info.major == 2:
        trans.install(unicode=True)
    else:
        trans.install()
    return language 
Example #14
Source File: test_gettext.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(UMOFILE, 'rb') as fp:
            self.t = gettext.GNUTranslations(fp)
        self._ = self.t.ugettext 
Example #15
Source File: trans_real.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kw):
        gettext_module.GNUTranslations.__init__(self, *args, **kw)
        self.set_output_charset('utf-8')
        self.django_output_charset = 'utf-8'
        self.__language = '??' 
Example #16
Source File: test_gettext.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(UMOFILE, 'rb') as fp:
            self.t = gettext.GNUTranslations(fp)
        self._ = self.t.gettext 
Example #17
Source File: test_gettext.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(MMOFILE, 'rb') as fp:
            try:
                self.t = gettext.GNUTranslations(fp)
            except:
                self.tearDown()
                raise 
Example #18
Source File: internationalization.py    From mau_mau_bot with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.translators = {
            locale: gettext.GNUTranslations(
                open(gettext.find(
                    GETTEXT_DOMAIN, GETTEXT_DIR, languages=[locale]
                ), 'rb')
            )
            for locale
            in available_locales.keys()
            if locale != 'en_US'  # No translation file for en_US
        }
        self.locale_stack = list() 
Example #19
Source File: trans_real.py    From python with Apache License 2.0 5 votes vote down vote up
def _add_fallback(self, localedirs=None):
        """Sets the GNUTranslations() fallback with the default language."""
        # Don't set a fallback for the default language or any English variant
        # (as it's empty, so it'll ALWAYS fall back to the default language)
        if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'):
            return
        if self.domain == 'django':
            # Get from cache
            default_translation = translation(settings.LANGUAGE_CODE)
        else:
            default_translation = DjangoTranslation(
                settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs
            )
        self.add_fallback(default_translation) 
Example #20
Source File: test_gettext.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(MMOFILE, 'rb') as fp:
            try:
                self.t = gettext.GNUTranslations(fp)
            except:
                self.tearDown()
                raise 
Example #21
Source File: trans_real.py    From python with Apache License 2.0 5 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'.
        """
        return gettext_module.translation(
            domain=self.domain,
            localedir=localedir,
            languages=[self.__locale],
            codeset='utf-8',
            fallback=use_null_fallback) 
Example #22
Source File: trans_real.py    From python with Apache License 2.0 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.set_output_charset('utf-8')  # For Python 2 gettext() (#25720)

        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 #23
Source File: trans_real.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _add_fallback(self, localedirs=None):
        """Set the GNUTranslations() fallback with the default language."""
        # Don't set a fallback for the default language or any English variant
        # (as it's empty, so it'll ALWAYS fall back to the default language)
        if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'):
            return
        if self.domain == 'django':
            # Get from cache
            default_translation = translation(settings.LANGUAGE_CODE)
        else:
            default_translation = DjangoTranslation(
                settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs
            )
        self.add_fallback(default_translation) 
Example #24
Source File: trans_real.py    From Hands-On-Application-Development-with-PyCharm 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 Hands-On-Application-Development-with-PyCharm 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: test_gettext.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(MMOFILE, 'rb') as fp:
            try:
                self.t = gettext.GNUTranslations(fp)
            except:
                self.tearDown()
                raise 
Example #27
Source File: test_gettext.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        GettextBaseTest.setUp(self)
        with open(UMOFILE, 'rb') as fp:
            self.t = gettext.GNUTranslations(fp)
        self._ = self.t.gettext 
Example #28
Source File: test_gettext.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_plural_form_error_issue17898(self):
        with open(MOFILE, 'wb') as fp:
            fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
        with open(MOFILE, 'rb') as fp:
            # If this runs cleanly, the bug is fixed.
            t = gettext.GNUTranslations(fp) 
Example #29
Source File: test_gettext.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_plural_forms2(self):
        eq = self.assertEqual
        with open(self.mofile, 'rb') as fp:
            t = gettext.GNUTranslations(fp)
        x = t.ngettext('There is %s file', 'There are %s files', 1)
        eq(x, 'Hay %s fichero')
        x = t.ngettext('There is %s file', 'There are %s files', 2)
        eq(x, 'Hay %s ficheros')

    # Examples from http://www.gnu.org/software/gettext/manual/gettext.html 
Example #30
Source File: test_gettext.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_plural_form_error_issue17898(self):
        with open(MOFILE, 'wb') as fp:
            fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898))
        with open(MOFILE, 'rb') as fp:
            # If this runs cleanly, the bug is fixed.
            t = gettext.GNUTranslations(fp)