本文整理汇总了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
示例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
示例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 = {}
示例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)
示例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
示例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
})
示例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 = {}
示例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.
示例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.
示例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.
示例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
示例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
示例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
示例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()
示例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