Python gettext.NullTranslations() Examples
The following are 30
code examples of gettext.NullTranslations().
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: i18n.py From Rqalpha-myquant-learning with Apache License 2.0 | 6 votes |
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()
Example #2
Source File: i18n.py From InplusTrader_Linux with MIT License | 6 votes |
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()
Example #3
Source File: i18n.py From InplusTrader_Linux with MIT License | 6 votes |
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()
Example #4
Source File: __init__.py From INGInious with GNU Affero General Public License v3.0 | 6 votes |
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 })
Example #5
Source File: parsable_text.py From INGInious with GNU Affero General Public License v3.0 | 6 votes |
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
Example #6
Source File: trans_real.py From openhgsenti with Apache License 2.0 | 6 votes |
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 #7
Source File: support.py From pySINDy with MIT License | 6 votes |
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 = {}
Example #8
Source File: support.py From pySINDy with MIT License | 6 votes |
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)
Example #9
Source File: i18n.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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.
Example #10
Source File: i18n.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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.
Example #11
Source File: i18n.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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.
Example #12
Source File: argument_parser.py From mocodo with MIT License | 6 votes |
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 #13
Source File: support.py From sndlatr with Apache License 2.0 | 6 votes |
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)
Example #14
Source File: support.py From sndlatr with Apache License 2.0 | 6 votes |
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 = {}
Example #15
Source File: i18n.py From googleapps-message-recall with Apache License 2.0 | 6 votes |
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
Example #16
Source File: trans_real.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #17
Source File: fakes.py From oslo.i18n with Apache License 2.0 | 6 votes |
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
Example #18
Source File: poster.py From GpxTrackPoster with MIT License | 6 votes |
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
Example #19
Source File: trans_real.py From python-compat-runtime with Apache License 2.0 | 5 votes |
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()
Example #20
Source File: testutils.py From jarvis with GNU General Public License v2.0 | 5 votes |
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)
Example #21
Source File: test.py From PeekabooAV with GNU General Public License v3.0 | 5 votes |
def main(): """ Run the testsuite. """ gettext.NullTranslations().install() suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestConfigParser)) suite.addTest(unittest.makeSuite(TestDefaultConfig)) suite.addTest(unittest.makeSuite(TestValidConfig)) suite.addTest(unittest.makeSuite(TestInvalidConfig)) suite.addTest(unittest.makeSuite(TestSample)) suite.addTest(unittest.makeSuite(TestDatabase)) suite.addTest(unittest.makeSuite(TestOletools)) suite.addTest(unittest.makeSuite(TestFiletools)) suite.addTest(unittest.makeSuite(TestRulesetEngine)) suite.addTest(unittest.makeSuite(TestRules)) suite.addTest(unittest.makeSuite(TestExpressionParser)) # TODO: We need more tests!!! # Disable all logging to avoid spurious messages. logging.disable(logging.ERROR) runner = unittest.TextTestRunner( verbosity=2, resultclass=PeekabooTestResult) result = runner.run(suite) logging.disable(logging.NOTSET) if not result.wasSuccessful(): sys.exit(1)
Example #22
Source File: i18n.py From canute-ui with GNU General Public License v3.0 | 5 votes |
def install(locale_code): try: translations = gettext.translation( 'canute', localedir='ui/locale', languages=[locale_code], fallback=False ) except OSError as e: log.warning(e) translations = gettext.NullTranslations() translations.install() # Before having installed _() we need extractors to see language titles. # It's convenient to have it act as the identity function, too.
Example #23
Source File: i18n.py From jarvis with GNU General Public License v2.0 | 5 votes |
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
Example #24
Source File: language_handler.py From yugioh-game with MIT License | 5 votes |
def _(self, lang, text): if lang == 'english': return gettext.NullTranslations().gettext(text) else: return gettext.translation('game', 'locale', languages=[self.get_language(lang)['short']], fallback=True).gettext(text)
Example #25
Source File: i18n.py From InplusTrader_Linux with MIT License | 5 votes |
def __init__(self, trans=None): self.trans = NullTranslations() if trans is None else trans
Example #26
Source File: trans_real.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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()
Example #27
Source File: obj_fixtures.py From oslo.versionedobjects with Apache License 2.0 | 5 votes |
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)
Example #28
Source File: trans_real.py From python with Apache License 2.0 | 5 votes |
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
Example #29
Source File: trans_real.py From python with Apache License 2.0 | 5 votes |
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)
Example #30
Source File: fixture.py From oslo.i18n with Apache License 2.0 | 5 votes |
def gettext(self, message): msg = gettext.NullTranslations.gettext(self, message) return self.prefix + msg