當前位置: 首頁>>代碼示例>>Python>>正文


Python gettext.NullTranslations方法代碼示例

本文整理匯總了Python中gettext.NullTranslations方法的典型用法代碼示例。如果您正苦於以下問題:Python gettext.NullTranslations方法的具體用法?Python gettext.NullTranslations怎麽用?Python gettext.NullTranslations使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gettext的用法示例。


在下文中一共展示了gettext.NullTranslations方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: translator

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
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 
開發者ID:openstack,項目名稱:oslo.i18n,代碼行數:24,代碼來源:fakes.py

示例2: _new_gnu_trans

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
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 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:22,代碼來源:trans_real.py

示例3: __init__

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def __init__(self, fp=None):
        """Initialize a simple translations class which is not backed by a
        real catalog. Behaves similar to gettext.NullTranslations but also
        offers Babel's on *gettext methods (e.g. 'dgettext()').

        :param fp: a file-like object (ignored in this class)
        """
        # These attributes are set by gettext.NullTranslations when a catalog
        # is parsed (fp != None). Ensure that they are always present because
        # some *gettext methods (including '.gettext()') rely on the attributes.
        self._catalog = {}
        self.plural = lambda n: int(n != 1)
        super(NullTranslations, self).__init__(fp=fp)
        self.files = filter(None, [getattr(fp, 'name', None)])
        self.domain = self.DEFAULT_DOMAIN
        self._domains = {} 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:18,代碼來源:support.py

示例4: load

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def load(cls, dirname=None, locales=None, domain=None):
        """Load translations from the given directory.

        :param dirname: the directory containing the ``MO`` files
        :param locales: the list of locales in order of preference (items in
                        this list can be either `Locale` objects or locale
                        strings)
        :param domain: the message domain (default: 'messages')
        """
        if locales is not None:
            if not isinstance(locales, (list, tuple)):
                locales = [locales]
            locales = [str(locale) for locale in locales]
        if not domain:
            domain = cls.DEFAULT_DOMAIN
        filename = gettext.find(domain, dirname, locales)
        if not filename:
            return NullTranslations()
        with open(filename, 'rb') as fp:
            return cls(fp=fp, domain=domain) 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:22,代碼來源:support.py

示例5: rst

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def rst(cls, string, show_everything=False, translation=gettext.NullTranslations(), initial_header_level=3,
            debug=False):
        """Parses reStructuredText"""
        overrides = {
            'initial_header_level': initial_header_level,
            'doctitle_xform': False,
            'syntax_highlight': 'none',
            'force_show_hidden_until': show_everything,
            'translation': translation,
            'raw_enabled': True,
            'file_insertion_enabled': False,
            'math_output': 'MathJax /this/does/not/need/to/exist.js'
        }
        if debug:
            overrides['halt_level'] = 2
            overrides['traceback'] = True
        parts = core.publish_parts(source=string, writer=_CustomHTMLWriter(),
                                   settings_overrides=overrides)
        return parts['body_pre_docinfo'] + parts['fragment']

# override base directives 
開發者ID:UCL-INGI,項目名稱:INGInious,代碼行數:23,代碼來源:parsable_text.py

示例6: __init__

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def __init__(self, context, backend_addr, friendly_name, concurrency, tasks_filesystem, course_factory):
        """
        :param context: ZeroMQ context for this process
        :param backend_addr: address of the backend (for example, "tcp://127.0.0.1:2222")
        :param friendly_name: a string containing a friendly name to identify agent
        :param tasks_filesystem: FileSystemProvider to the course/tasks
        :param course_factory: Course factory used to get course/tasks
        """
        super().__init__(context, backend_addr, friendly_name, concurrency, tasks_filesystem)
        self._logger = logging.getLogger("inginious.agent.mcq")
        self.course_factory = course_factory

        # Init gettext
        self._translations = {"en": gettext.NullTranslations()}
        available_translations = [x for x in os.listdir(get_root_path() + '/agent/mcq_agent/i18n') if os.path.isdir(os.path.join(get_root_path() + '/agent/mcq_agent/i18n', x))]
        self._translations.update({
            lang: gettext.translation('messages', get_root_path() + '/agent/mcq_agent/i18n', [lang]) for lang in available_translations
        }) 
開發者ID:UCL-INGI,項目名稱:INGInious,代碼行數:20,代碼來源:__init__.py

示例7: __init__

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def __init__(self, fp=None):
        """Initialize a simple translations class which is not backed by a
        real catalog. Behaves similar to gettext.NullTranslations but also
        offers Babel's on *gettext methods (e.g. 'dgettext()').

        :param fp: a file-like object (ignored in this class)
        """
        # These attributes are set by gettext.NullTranslations when a catalog
        # is parsed (fp != None). Ensure that they are always present because
        # some *gettext methods (including '.gettext()') rely on the attributes.
        self._catalog = {}
        self.plural = lambda n: int(n != 1)
        super(NullTranslations, self).__init__(fp=fp)
        self.files = list(filter(None, [getattr(fp, 'name', None)]))
        self.domain = self.DEFAULT_DOMAIN
        self._domains = {} 
開發者ID:luckystarufo,項目名稱:pySINDy,代碼行數:18,代碼來源:support.py

示例8: __init__

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def __init__(self, name: str = None, language: str = "default") -> None: #pylint: disable=bad-whitespace
        """Creates a new catalogue.

        :param name: The name of the catalog to load.
        :param language: The language to load. Valid values are language codes or
        "default". When "default" is specified, the language to load will be
        determined based on the system"s language settings.

        :note When `language` is `default`, the language to load can be
        overridden using the "LANGUAGE" environment variable.
        """

        self.__name = name
        self.__language = language
        self.__translation = None   # type: Optional[gettext.NullTranslations]
        self.__require_update = True
        self._update() #Load the actual translation document now that the language is set. 
開發者ID:Ultimaker,項目名稱:Uranium,代碼行數:19,代碼來源:i18n.py

示例9: i18n

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def i18n(self, text: str, *args: Any) -> str:
        """Mark a string as translateable.

        :param text: The string to mark as translatable
        :param args: Formatting arguments. These will replace formatting elements
                     in the translated string. See python str.format().
        :return: The translated text or the untranslated text if no translation
        was found.
        """


        if self.__require_update:
            self._update()

        translated = text  # Default to hard-coded text if no translation catalogue is loaded.
        if self.hasTranslationLoaded():
            translated = cast(gettext.NullTranslations, self.__translation).gettext(text)

        if args:
            translated = translated.format(*args)  # Positional arguments are replaced in the (translated) text.
        return self._replaceTags(translated)  # Also replace the global keys. 
開發者ID:Ultimaker,項目名稱:Uranium,代碼行數:23,代碼來源:i18n.py

示例10: i18nc

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def i18nc(self, context: str, text: str, *args: Any) -> str:
        """Mark a string as translatable and provide a context for translators.

        :param context: The context of the string, i.e. something that explains
        the use of the text.
        :param text: The text to mark translatable.
        :param args: Formatting arguments. These will replace formatting elements
        in the translated string. See python ``str.format()``.
        :return: The translated text or the untranslated text if it was not found
        in this catalog.
        """

        if self.__require_update:
            self._update()

        translated = text  # Default to hard-coded text if no translation catalogue is loaded.
        if self.hasTranslationLoaded():
            message_with_context = "{0}\x04{1}".format(context, text)  # \x04 is "end of transmission" byte, indicating to gettext that they are two different texts.
            message = cast(gettext.NullTranslations, self.__translation).gettext(message_with_context)
            if message != message_with_context:
                translated = message

        if args:
            translated = translated.format(*args)  # Positional arguments are replaced in the (translated) text.
        return self._replaceTags(translated)  # Also replace the global keys. 
開發者ID:Ultimaker,項目名稱:Uranium,代碼行數:27,代碼來源:i18n.py

示例11: get_translations

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def get_translations(self, locale):
        """Returns a translation catalog for a locale.

        :param locale:
            A locale code.
        :returns:
            A ``babel.support.Translations`` instance, or
            ``gettext.NullTranslations`` if none was found.
        """
        trans = self.translations.get(locale)
        if not trans:
            locales = (locale, self.default_locale)
            trans = self.load_translations(self.translations_path, locales,
                                           self.domains)
            if not webapp2.get_app().debug:
                self.translations[locale] = trans

        return trans 
開發者ID:google,項目名稱:googleapps-message-recall,代碼行數:20,代碼來源:i18n.py

示例12: set_language

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def set_language(self, language):
        if language:
            try:
                locale.setlocale(locale.LC_ALL, f"{language}.utf8")
            except locale.Error as e:
                print(f'Cannot set locale to "{language}": {e}')
                language = None
                pass

        # Fall-back to NullTranslations, if the specified language translation cannot be found.
        if language:
            lang = gettext.translation(
                "gpxposter", localedir="locale", languages=[language], fallback=True
            )
        else:
            lang = gettext.NullTranslations()
        self.trans = lang.gettext 
開發者ID:flopp,項目名稱:GpxTrackPoster,代碼行數:19,代碼來源:poster.py

示例13: init_localization

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
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 
開發者ID:laowantong,項目名稱:mocodo,代碼行數:22,代碼來源:argument_parser.py

示例14: set_locale

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def set_locale(self, locales, trans_dir=None):
        if locales[0] is None or "en" in locales[0].lower():
            self.trans = NullTranslations()
            return
        if "cn" in locales[0].lower():
            locales = ["zh_Hans_CN"]
        try:
            if trans_dir is None:
                trans_dir = os.path.join(
                    os.path.dirname(
                        os.path.abspath(
                            __file__,
                        ),
                    ),
                    "translations"
                )
            self.trans = translation(
                domain="messages",
                localedir=trans_dir,
                languages=locales,
            )
        except Exception as e:
            system_log.debug(e)
            self.trans = NullTranslations() 
開發者ID:zhengwsh,項目名稱:InplusTrader_Linux,代碼行數:26,代碼來源:i18n.py

示例15: __init__

# 需要導入模塊: import gettext [as 別名]
# 或者: from gettext import NullTranslations [as 別名]
def __init__(self, fp=None, prefix='noprefix'):
        gettext.NullTranslations.__init__(self, fp)
        self.prefix = prefix 
開發者ID:openstack,項目名稱:oslo.i18n,代碼行數:5,代碼來源:fixture.py


注:本文中的gettext.NullTranslations方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。