我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gettext.install()。
def display_metadata(self, term_instance): """ Sends a message to the user that displays the OGG file metadata. Things like ID3 tags, bitrate, channels, etc. """ if not self.sent_message: global _logged_mutagen_warning try: import mutagen.oggvorbis except ImportError: if not _logged_mutagen_warning: _logged_mutagen_warning = True logging.warning(_( "Could not import the mutagen Python module. " "Displaying audio file metadata will be disabled.")) logging.info(_( "TIP: Install mutagen: sudo pip install mutagen")) return oggfile = mutagen.oggvorbis.Open(self.file_obj.name) message = "<pre>%s</pre>" % oggfile.pprint() term_instance.send_message(message) self.sent_message = True
def activateLanguage(self, index): try: lang = self.lang[index] print "Activating language " + lang[0] self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index], fallback=True) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: if x: x() except: print "Selected language does not exist!" # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails. # We'd rather try to set all available categories, and ignore the others for category in [locale.LC_CTYPE, locale.LC_COLLATE, locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES, locale.LC_NUMERIC]: try: locale.setlocale(category, (self.getLanguage(), 'UTF-8')) except: pass # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8' os.environ["LANGUAGE"] = self.getLanguage() + '.UTF-8' os.environ["GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
def enable_lazy(): """Convenience function for configuring _() to use lazy gettext Call this at the start of execution to enable the gettextutils._ function to use lazy gettext functionality. This is useful if your project is importing _ directly instead of using the gettextutils.install() way of importing the _ function. """ # FIXME(dhellmann): This function will be removed in oslo.i18n, # because the TranslatorFactory makes it superfluous. global _, _LI, _LW, _LE, _LC, USE_LAZY tf = TranslatorFactory('kingbirdclient', lazy=True) _ = tf.primary _LI = tf.log_info _LW = tf.log_warning _LE = tf.log_error _LC = tf.log_critical USE_LAZY = True
def activateLanguage(self, index): try: lang = self.lang[index] print "Activating language " + lang[0] self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index], fallback=True) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: x() except: print "Selected language does not exist!" # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails. # We'd rather try to set all available categories, and ignore the others for category in [locale.LC_CTYPE, locale.LC_COLLATE, locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES, locale.LC_NUMERIC]: try: locale.setlocale(category, (self.getLanguage(), 'UTF-8')) except: pass # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8' os.environ["LANGUAGE"] = self.getLanguage() + '.UTF-8' os.environ["GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install() eq(_('mullusk'), 'bacon') # Test installation of other methods import builtins t.install(names=["gettext", "lgettext"]) eq(_, t.gettext) eq(builtins.gettext, t.gettext) eq(lgettext, t.lgettext) del builtins.gettext del builtins.lgettext
def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install(unicode=True) eq(_('mullusk'), 'bacon') # Test installation of other methods import __builtin__ t.install(unicode=True, names=["gettext", "lgettext"]) eq(_, t.ugettext) eq(__builtin__.gettext, t.ugettext) eq(lgettext, t.lgettext) del __builtin__.gettext del __builtin__.lgettext
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 install(domain): """Install a _() function using the given translation domain. Given a translation domain, install a _() function using gettext's install() function. The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specific environment variable (e.g. NOVA_LOCALEDIR). Note that to enable lazy translation, enable_lazy must be called. :param domain: the translation domain """ from six import moves tf = TranslatorFactory(domain) moves.builtins.__dict__['_'] = tf.primary
def activateLanguage(self, index): try: lang = self.lang[index] print "[Language] Activating language " + lang[0] self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index]) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: if x: x() except: print "[Language] Selected language does not exist!" # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails. # We'd rather try to set all available categories, and ignore the others for category in [locale.LC_CTYPE, locale.LC_COLLATE, locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES, locale.LC_NUMERIC]: try: locale.setlocale(category, (self.getLanguage(), 'UTF-8')) except: pass # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8' os.environ["LANGUAGE"] = self.getLanguage() + '.UTF-8' os.environ["GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
def spellcheck(self): global spell_support spell_error = False if self.posix and spell_support: if self.config.get('gtkspell', False, section='spell') == True: if self.config.get('notes', True, section='spell') is True and self.config.get('lang', section='spell') != '': try: self.notes_spell = gtkspell.Spell(self.widgets['add']['notes'], self.config.get('lang', section='spell')) except: spell_error = True if self.config.get('plot', True, section='spell') is True and self.config.get('lang', section='spell') != '': try: self.plot_spell = gtkspell.Spell(self.widgets['add']['plot'], self.config.get('lang', section='spell')) except: spell_error = True if spell_error: log.info('Dictionary not available. Spell check will be disabled.') if not self.config.get('notified', False, section='spell'): gutils.info(_("Dictionary not available. Spellcheck will be disabled. \n" + \ "Please install the aspell-%s package or adjust the spellchecker preferences.") % self.config.get('lang', section='spell'), \ self.widgets['preferences']['window']) self.config.set('notified', True, section='spell') self.config.save() else: log.info('Spellchecker is not available')
def install_updates(self): if self.stopped: wx.CallAfter(Publisher().sendMessage, "update","Aborted") return 0 try: wx.CallAfter(Publisher().sendMessage, "update","Installing updates....") if self.SU.install(self.DB)==0: #successful if return value 0 wx.CallAfter(Publisher().sendMessage, "update","Installation completed") else: wx.CallAfter(Publisher().sendMessage, "error_report","Error in installation process") return 0 except: wx.CallAfter(Publisher().sendMessage, "error_report","Installation failed") return 0 return True
def install(op, api_inst, pargs, accept, act_timeout, backup_be, backup_be_name, be_activate, be_name, li_ignore, li_erecurse, li_parent_sync, new_be, noexecute, origins, parsable_version, quiet, refresh_catalogs, reject_pats, show_licenses, stage, update_index, verbose): """Attempt to take package specified to INSTALLED state. The operands are interpreted as glob patterns.""" out_json = client_api._install(op, api_inst, pargs, accept, act_timeout, backup_be, backup_be_name, be_activate, be_name, li_ignore, li_erecurse, li_parent_sync, new_be, noexecute, origins, parsable_version, quiet, refresh_catalogs, reject_pats, show_licenses, stage, update_index, verbose, display_plan_cb=display_plan_cb, logger=logger) return __handle_client_json_api_output(out_json, op, api_inst)
def _api_install(self, api_obj, pkg_list, catch_wsie=True, show_licenses=False, accept_licenses=False, noexecute=False, **kwargs): self.debug("install {0}".format(" ".join(pkg_list))) plan = None for pd in api_obj.gen_plan_install(pkg_list, noexecute=noexecute, **kwargs): if plan is not None: continue plan = api_obj.describe() # update license status for pfmri, src, dest, accepted, displayed in \ plan.get_licenses(): api_obj.set_plan_license_status(pfmri, dest.license, displayed=show_licenses, accepted=accept_licenses) if noexecute: return self._api_finish(api_obj, catch_wsie=catch_wsie)
def activateLanguage(self, index): try: lang = self.lang[index] print "Activating language " + lang[0] if pathExists(resolveFilename(SCOPE_GOSLANGUAGE, "%s/LC_MESSAGES/enigma2.mo") % str(lang[1]) ): self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_GOSLANGUAGE, ""), languages=[index]) else: self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index]) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: x() except: print "Selected language does not exist!" # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails. # We'd rather try to set all available categories, and ignore the others for category in [locale.LC_CTYPE, locale.LC_COLLATE, locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES, locale.LC_NUMERIC]: try: locale.setlocale(category, (self.getLanguage(), 'UTF-8')) except: pass # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8' os.environ["GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
def activateLanguage(self, index): try: if index not in self.lang: print "Selected language %s does not exist, fallback to en_EN!" % index index = "en_EN" lang = self.lang[index] print "Activating language " + lang[0] self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index]) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: x() except: print "Error in activating language!" # NOTE: we do not use LC_ALL, because LC_ALL will not set any of the categories, when one of the categories fails. # We'd rather try to set all available categories, and ignore the others for category in [locale.LC_CTYPE, locale.LC_COLLATE, locale.LC_TIME, locale.LC_MONETARY, locale.LC_MESSAGES, locale.LC_NUMERIC]: try: locale.setlocale(category, (self.getLanguage(), 'UTF-8')) except: pass # HACK: sometimes python 2.7 reverts to the LC_TIME environment value, so make sure it has the correct value os.environ["LC_TIME"] = self.getLanguage() + '.UTF-8' #os.environ["GST_SUBTITLE_ENCODING"] = self.getGStreamerSubtitleEncoding()
def __init__(self): gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8") gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE)) gettext.textdomain("enigma2") self.activeLanguage = 0 self.catalog = None self.lang = {} self.InitLang() self.callbacks = []
def install(domain, lazy=False): """Install a _() function using the given translation domain. Given a translation domain, install a _() function using gettext's install() function. The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specific environment variable (e.g. NOVA_LOCALEDIR). :param domain: the translation domain :param lazy: indicates whether or not to install the lazy _() function. The lazy _() introduces a way to do deferred translation of messages by installing a _ that builds Message objects, instead of strings, which can then be lazily translated into any available locale. """ if lazy: from six import moves tf = TranslatorFactory(domain, lazy=True) moves.builtins.__dict__['_'] = tf.primary else: localedir = '%s_LOCALEDIR' % domain.upper() if six.PY3: gettext.install(domain, localedir=os.environ.get(localedir)) else: gettext.install(domain, localedir=os.environ.get(localedir), unicode=True)
def set_locale(self, language_code, reuse=True): """update localization Args: language_code: string, a known translation code reuse: string, toggle to True to use a cached translation Returns: boolean, True on success """ if not reuse or language_code not in self._locales: try: self._locales[language_code] = gettext.translation( "hangupsbot", languages=[language_code], localedir=os.path.join(os.path.dirname(__file__), "locale")) logger.debug("locale loaded: %s", language_code) except OSError: logger.exception("no translation for %s", language_code) if language_code in self._locales: self._locales[language_code].install() logger.info("locale set to %s", language_code) return True logger.warning("LOCALE %s is not available", language_code) return False
def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir self.mofile = MOFILE gettext.install('gettext', self.localedir)
def do_activate(self): GObject.threads_init() gettext.install('easy-ebook-viewer', '/usr/share/easy-ebook-viewer/locale') # We only allow a single window and raise any existing ones if not self.window: # Windows are associated with the application # when the last one is closed the application shuts down self.window = MainWindow(file_path=self.file_path) self.window.connect("delete-event", self.on_quit) self.window.set_wmclass("easy-ebook-viewer", "easy-ebook-viewer") self.window.show_all() if not self.window.book_loaded: self.window.header_bar_component.hide_jumping_navigation() Gtk.main()
def init_locale(): global INIT try: INIT except: gettext.install(PACKAGE, unicode=True) INIT = True
def set_language(message): lang = get_language(message) languages[Language(lang)].install() # Allow to change the language used on a server # Parameters: # - message: discord message, the message which called this function # - lang: Language, the language to set # Return: # - msg: str, message returned by the bot
def enable_lazy(): """Convenience function for configuring _() to use lazy gettext Call this at the start of execution to enable the gettextutils._ function to use lazy gettext functionality. This is useful if your project is importing _ directly instead of using the gettextutils.install() way of importing the _ function. """ global USE_LAZY USE_LAZY = True
def initiate_I18N(self): default_locale, encoding = locale.getdefaultlocale() self.available_languages = collections.OrderedDict() self.available_languages['System locale'] = default_locale self.available_languages['Dansk'] = 'da_DK' self.available_languages['English'] = 'en_US' gettext.install('worksets', self.LOCALE_DIR) self.change_language(self.language)
def change_language(self, language_name): lang_code = self.available_languages[language_name] language = gettext.translation('worksets', self.LOCALE_DIR, languages=[lang_code]) language.install()
def i18n(self, location): gettext.bindtextdomain('griffith', location) gettext.textdomain('griffith') gtk.glade.bindtextdomain('griffith', location) gtk.glade.textdomain('griffith') gettext.install('griffith', location, unicode=1)
def install(self,DB): import stat self.backup_db(DB) '''output=Popen(['gksudo','rmdir','/var/21'],stdout=PIPE,stderr=PIPE) output = p.stdout.read() print output ''' #print subprocess.check_call('cd /tmp/smart_school', shell=True)# IF OUT PUT 0 success, if 1, fail, 3 password error #print subprocess.call('gksu chmod +x /tmp/smart_school/install.sh',shell=True,stderr=subprocess.STDOUT)# IF OUT PUT 0 success, if 1, fail, 3 password error os.chmod('/tmp/smart_school/install.sh', stat.S_IEXEC) output=subprocess.call('cd /tmp/smart_school\ngksu ./install.sh',shell=True)#,stderr=subprocess.STDOUT)# IF OUT PUT 0 success, if 1, fail, 3 password error return output # success if out put is 0
def __init__(self,check=True,install=False): """Init Worker Thread Class.""" Thread.__init__(self) self.SU=software_update() self.check_only=check # True if need to run functions to check for installation self.install_only=install self.stopped=False self.start() # start the thread
def on_install(self, event): # wxGlade: update_win.<event_handler> #self.play_animation('') if self.button_install.Label=="Check for Update": self.button_install.Enable(False) self.thread=update_thread(check=True,install=False) self.progress_bar.Hide() elif self.button_install.Label=="Install Update": #intallhere self.button_install.Enable(False) self.progress_bar.Show() self.thread=update_thread(check=False,install=True) event.Skip()
def bindtextdomain(app_name, locale_dir=None): """ Bind the domain represented by app_name to the locale directory locale_dir. It has the effect of loading translations, enabling applications for different languages. app_name: a domain to look for translations, tipically the name of an application. locale_dir: a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo If omitted or None, then the current binding for app_name is used. """ try: import locale import gettext locale.setlocale(locale.LC_ALL, "") gtk.glade.bindtextdomain(app_name, locale_dir) gettext.install(app_name, locale_dir, unicode=1) except (IOError,locale.Error), e: #force english as default locale try: os.environ["LANGUAGE"] = "en_US.UTF-8" locale.setlocale(locale.LC_ALL, "en_US.UTF-8") gtk.glade.bindtextdomain(app_name, locale_dir) gettext.install(app_name, locale_dir, unicode=1) return except: #english didnt work, just use spanish try: __builtins__.__dict__["_"] = lambda x : x except: __builtins__["_"] = lambda x : x
def __init__(self, **kwargs): self.ui = None GObject.threads_init() listen() Gtk.Application.__init__(self, application_id='com.github.geigi.cozy') GLib.setenv("PULSE_PROP_media.role", "music", True) import gettext locale.bindtextdomain('cozy', localedir) locale.textdomain('cozy') gettext.install('cozy', localedir)
def __handle_client_json_api_output(out_json, op, api_inst): """This is the main client_json_api output handling function used for install, update and uninstall and so on.""" if "errors" in out_json: _generate_error_messages(out_json["status"], out_json["errors"], cmd=op) if "data" in out_json and "repo_status" in out_json["data"]: display_repo_failures(out_json["data"]["repo_status"]) __display_plan_messages(api_inst, frozenset([OP_STAGE_PREP, OP_STAGE_EXEC])) return out_json["status"]
def install(domain, localedir): ''' :param domain: translation domain :param localedir: locale directory Installs the function _() in Python’s builtin namespace, based on domain and localedir. Codeset is always UTF-8. As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the _() function, like this: .. sourcecode:: python import elib.intl elib.intl.install('myapplication', '/path/to/usr/share/locale') print _('This string will be translated.') Note that this is only one way, albeit the most convenient way, to make the _() function available to your application. Because it affects the entire application globally, and specifically Python’s built-in namespace, localized modules should never install _(). Instead, you should use :func:`elib.intl.install_module` to make _() available to your module. ''' _install(domain, localedir, True) gettext.install(domain, localedir, unicode=True)
def add_to_desktop(self, widget, desktopEntry): subprocess.call(['xdg-desktop-icon', 'install', '--novendor', desktopEntry.desktopFile])