我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用gettext.NullTranslations()。
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()
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 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 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 _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 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
def get_translation_for(self, locale, domain): translation = self.translations.get((locale, domain), None) if not translation: with self.map_lock: for package in ReahlSystemConfig().translation_packages: for locale_dir in package.__path__: if not isinstance(translation, Translations): translation = Translations.load(dirname=locale_dir, locales=[locale], domain=domain) # Babel 1.3 bug under Python 3: files is a filter object, not a list like in Python 2 translation.files = list(translation.files) else: translation.merge(Translations.load(dirname=locale_dir, locales=[locale], domain=domain)) self.translations[(locale, domain)] = translation return translation or gettext.NullTranslations()
def get_plugin_instance(plugin_class, *extra_args): info = type('', (object,), { 'name': 'pluginunittest', 'translations': {'en-US': gettext.NullTranslations()}})() args = tuple(extra_args) + (info, TEST_PROFILE) return plugin_class(*args)
def parse_translations(translations_path): translations = {} if os.path.isdir(translations_path): for content in os.listdir(translations_path): if not os.path.isdir(os.path.join(translations_path, content)): lang, ext = os.path.splitext(content) if ext == (os.extsep + 'mo') and RE_TRANSLATIONS.match(lang): with open(os.path.join(translations_path, content), mode="rb") as f: translations[lang] = gettext.GNUTranslations(f) if not translations: # Untranslated module, assume hardcoded en-US strings translations['en-US'] = gettext.NullTranslations() return translations
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[currentThread()] = gettext_module.NullTranslations()
def app(postgres, mocker, caplog): caplog.set_level(logging.WARNING, logger='ckan.lib.i18n') caplog.set_level(logging.WARNING, logger='migrate') caplog.set_level(logging.WARNING, logger='pyutilib') caplog.set_level(logging.WARNING, logger='vdm') caplog.set_level(logging.WARNING, logger='pysolr') global_config = { '__file__': '', 'here': os.path.dirname(__file__), 'ckan.site_url': 'http://localhost', 'ckan.plugins': 'harvest odgovlt_harvester', 'sqlalchemy.url': postgres, 'ckanext.harvest.user_name': 'harvest', # 'solr_url': 'http://127.0.0.1:8983/solr/ckan', } app_config = { 'who.config_file': pres.resource_filename('ckan.config', 'who.ini'), 'beaker.session.secret': 'secret', } app = ckan.config.middleware.make_app(global_config, **app_config) app = CKANTestApp(app) ckan.model.repo.init_db() ckanext.harvest.model.setup() pylons.translator = gettext.NullTranslations() return app
def init_localization(): # pragma: no cover """ Application localization :return: gettext translator method :rtype: method """ try: # Language message file if 'win32' not in sys.platform: lang_filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), "LC_MESSAGES/%s.mo" % get_app_config('Alignak-app', 'locale') ) else: lang_filename = get_main_folder() + "\\locales\\%s.mo" % get_app_config( 'Alignak-app', 'locale' ) logger.info( "Opening message file %s for locale %s", lang_filename, get_app_config('Alignak-app', 'locale') ) translation = GNUTranslations(open(lang_filename, "rb")) translation.install() _ = translation.gettext except IOError: logger.warning("Locale not found. Using default language messages (English)") null_translation = NullTranslations() null_translation.install() _ = null_translation.gettext except Exception as e: # pragma: no cover - should not happen logger.error("Locale not found. Exception: %s", str(e)) null_translation = NullTranslations() null_translation.install() _ = null_translation.gettext return _
def i18n_wrapper(locale: Optional[str] = None) -> Any: """ Internationalize using gettext. Returns gettext for provided locale or default (zentropi.defaults.LOCALE). Example: >>> from zentropi.utils import i18n_wrapper >>> _ = i18n_wrapper() >>> print(_('Hello, world.')) Hello, world. """ from zentropi import BASE_PATH from zentropi.defaults import LOCALE locale = locale or lib_locale.getlocale()[0] or LOCALE locale_dir = os.path.join(BASE_PATH, 'locale') locale_file = os.path.join(locale_dir, '{}.mo'.format(locale)) try: translation = gettext.GNUTranslations(open(locale_file, 'rb')) except IOError: warnings.warn('Translation file for {} not found at: {}. Using default.' ''.format(locale, locale_file)) translation = gettext.NullTranslations() # type: ignore translation.install() return translation.gettext