def changeLanguage(self, language):
"""Change the language."""
try:
lang = gettext.translation(
'messages', localedir='locales', languages=[language])
lang.install()
except:
lang = gettext.NullTranslations()
self.app.removeTranslator(self.translator)
self.translator = PyQt5.QtCore.QTranslator(self.app)
self.translator.load(PyQt5.QtCore.QLocale(language),
"qtbase", "_", scctool.settings.getAbsPath('locales'), ".qm")
self.app.installTranslator(self.translator)
scctool.settings.config.parser.set("SCT", "language", language)
self.restart()
python类NullTranslations()的实例源码
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 = {}
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)
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
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()
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()
def gettext_for(lang):
"""
Return a GNUTranslation class for the given language.
Example:
>>> trans = gettext_for('pt_BR')
>>> _ = trans.gettext
>>> _('hello world!') # doctest: +SKIP
'olá mundo!'
"""
lang = lang.replace('-', '_')
try:
with open(os.path.join(L10N_PATH, lang + '.mo'), 'rb') as F:
result = gettext.GNUTranslations(F)
except FileNotFoundError:
result = gettext.NullTranslations()
return result
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 = {}
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)
def initGetText(domain, install=False, fallback=True):
locale_paths = [
Path(__file__).parent / ".." / "locale",
Path(sys.prefix) / "share" / "locale",
]
locale_dir, translation = None, None
for locale_dir in [d for d in locale_paths if d.exists()]:
if gettext.find(domain, str(locale_dir)):
log.debug("Loading message catalogs from {}".format(locale_dir))
translation = gettext.translation(domain, str(locale_dir))
break
if translation is None:
# This with either throw FileNotFoundError (fallback=False) or set a
# gettext.NullTranslations
translation = gettext.translation(domain, str(locale_dir),
fallback=fallback)
assert translation
if install:
gettext.install(domain, str(locale_dir), names=["ngettext"])
return translation
def __init__(self, translate=NullTranslations(), ignore_tags=IGNORE_TAGS,
include_attrs=INCLUDE_ATTRS, extract_text=True):
"""Initialize the translator.
:param translate: the translation function, for example ``gettext`` or
``ugettext``.
:param ignore_tags: a set of tag names that should not be localized
:param include_attrs: a set of attribute names should be localized
:param extract_text: whether the content of text nodes should be
extracted, or only text in explicit ``gettext``
function calls
:note: Changed in 0.6: the `translate` parameter can now be either
a ``gettext``-style function, or an object compatible with the
``NullTransalations`` or ``GNUTranslations`` interface
"""
self.translate = translate
self.ignore_tags = ignore_tags
self.include_attrs = include_attrs
self.extract_text = extract_text
def _setup_locale():
""" Setting up localization
:return: translation method
"""
try:
locale_file = Config.get('xpopup', 'locale_file')
except:
from os.path import abspath, dirname, join
locale_file = join(dirname(abspath(__file__)), 'xpopup.mo')
try:
with open(locale_file, "rb") as f:
xpopup_locale = gettext.GNUTranslations(f)
Logger.info('Localization file loaded (%s).' % locale_file)
except Exception as e:
Logger.warning('%s: %s. Switch to the defaults.' %
(e.__class__.__name__, str(e)))
xpopup_locale = gettext.NullTranslations()
if PY2:
return xpopup_locale.ugettext
else:
return xpopup_locale.gettext
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
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 = {}
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)
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()
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 = {}
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)
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
def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found (generally Django's).
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog)
def deactivate_all():
"""
Makes 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
def __init__(self, locale_code):
"""
Initialize GetText
:param locale_code selected locale
"""
try:
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'locale', '{}.mo'.format(locale_code))
trans = gettext.GNUTranslations(open(filename, "rb"))
logger.debug('{} Loaded'.format(filename))
except IOError:
logger.debug('Failed to found locale {}'.format(locale_code))
trans = gettext.NullTranslations()
trans.install()
def load_translations(self, dirname, locales, domains):
"""Loads a translation catalog.
:param dirname:
Path to where translations are stored.
:param locales:
A list of locale codes.
:param domains:
A list of domains to be merged.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.
"""
trans = None
trans_null = None
for domain in domains:
_trans = support.Translations.load(dirname, locales, domain)
if isinstance(_trans, NullTranslations):
trans_null = _trans
continue
elif trans is None:
trans = _trans
else:
trans.merge(_trans)
return trans or trans_null or NullTranslations()
def __init__(self, trans=None):
self.trans = NullTranslations() if trans is None else trans
def __init__(self, trans=None):
self.trans = NullTranslations() if trans is None else trans
def setUp(self):
super(TranslationFixture, self).setUp()
nulltrans = gettext.NullTranslations()
gettext_fixture = fixtures.MonkeyPatch('gettext.translation',
lambda *x, **y: nulltrans)
self.gettext_patcher = self.useFixture(gettext_fixture)
def __call__(self, language_code=None):
languages = (None if language_code is None else [language_code])
try:
return gettext.translation(
self.name, self.folder, languages)
except IOError:
return gettext.NullTranslations()
def __init__(self, locale_code):
"""
Initialize GetText
:param locale_code selected locale
"""
try:
filename = os.path.join('/usr/share/harbour-sailcron/python/cron_descriptor/locale', '{}.mo'.format(locale_code))
trans = gettext.GNUTranslations(open(filename, "rb"))
logger.debug('{} Loaded'.format(filename))
except IOError:
logger.debug('Failed to found locale {}'.format(locale_code))
trans = gettext.NullTranslations()
trans.install()
def render(template_name, extra_environments=None, **kwargs):
"""??? ???? jinja? ??????
:param template_name:
:return:
"""
if extra_environments is None:
extra_environments = {}
default_loader = PackageLoader('dodotable', 'templates')
loader = extra_environments.get(
'template_loader',
default_loader)
if not loader:
loader = default_loader
get_translations = extra_environments.get('get_translations')
env = Environment(loader=loader,
extensions=['jinja2.ext.i18n', 'jinja2.ext.with_'],
autoescape=True)
env.globals.update(extra_environments)
translations = get_translations() if callable(get_translations) else None
if translations is None:
translations = gettext.NullTranslations()
env.install_gettext_translations(translations)
template = env.get_template(template_name)
return template.render(**kwargs)
def init(locale_dirs, language, catalog='sphinx', charset='utf-8'):
"""Look for message catalogs in `locale_dirs` and *ensure* that there is at
least a NullTranslations catalog set in `translators`. If called multiple
times or if several ``.mo`` files are found, their contents are merged
together (thus making ``init`` reentrable).
"""
global translators
translator = translators.get(catalog)
# ignore previously failed attempts to find message catalogs
if isinstance(translator, gettext.NullTranslations):
translator = None
# the None entry is the system's default locale path
has_translation = True
# compile mo files if po file is updated
# TODO: remove circular importing
from sphinx.util.i18n import find_catalog_source_files
for catinfo in find_catalog_source_files(locale_dirs, language, domains=[catalog],
charset=charset):
catinfo.write_mo(language)
# loading
for dir_ in locale_dirs:
try:
trans = gettext.translation(catalog, localedir=dir_,
languages=[language])
if translator is None:
translator = trans
else:
translator._catalog.update(trans._catalog)
except Exception:
# Language couldn't be found in the specified path
pass
# guarantee translators[catalog] exists
if translator is None:
translator = gettext.NullTranslations()
has_translation = False
translators[catalog] = translator
if hasattr(translator, 'ugettext'):
translator.gettext = translator.ugettext
return translator, has_translation