我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用locale.setlocale()。
def reset_matplotlib(): """ Reset matplotlib to a common default. """ # Set all default values. mpl.rcdefaults() # Force agg backend. plt.switch_backend('agg') # These settings must be hardcoded for running the comparision tests and # are not necessarily the default values. mpl.rcParams['font.family'] = 'Bitstream Vera Sans' mpl.rcParams['text.hinting'] = False # Not available for all matplotlib versions. try: mpl.rcParams['text.hinting_factor'] = 8 except KeyError: pass import locale locale.setlocale(locale.LC_ALL, str('en_US.UTF-8')) # Most generic way to get the data folder path.
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return FalseoutputPoin ## =================================================================================== ## MAIN
def main(args=None): if args is None: args = sys.argv[1:] # Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger() autocomplete() try: cmd_name, cmd_args = parseopts(args) except PipError as exc: sys.stderr.write("ERROR: %s" % exc) sys.stderr.write(os.linesep) sys.exit(1) # Needed for locale.getpreferredencoding(False) to work # in pip._internal.utils.encoding.auto_decode try: locale.setlocale(locale.LC_ALL, '') except locale.Error as e: # setlocale can apparently crash if locale are uninitialized logger.debug("Ignoring error %s when setting locale", e) command = commands_dict[cmd_name](isolated=check_isolated(cmd_args)) return command.main(cmd_args)
def main(args=None): if args is None: args = sys.argv[1:] # Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger() autocomplete() try: cmd_name, cmd_args = parseopts(args) except PipError as exc: sys.stderr.write("ERROR: %s" % exc) sys.stderr.write(os.linesep) sys.exit(1) # Needed for locale.getpreferredencoding(False) to work # in pip.utils.encoding.auto_decode locale.setlocale(locale.LC_ALL, '') command = commands_dict[cmd_name](isolated=check_isolated(cmd_args)) return command.main(cmd_args) # ########################################################### # # Writing freeze files
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 process_request(self, request): # Under Windows, locale names are different, setlocale() with regular # locale names will fail and locale.setlocale(locale.LC_ALL, '') will # produce side effect seems like the safest option is just not set any # locale at all if os.name == 'nt': return # FIXME: some languages like arabic don't have a language only locale # for no good reason. we need a function to pick default locale for # these lang = translation.to_locale(translation.get_language()) try: if lang == 'tr' or lang.startswith('tr_'): raise ValueError("Turkish locale broken due to changed " "meaning of lower()") locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('Failed to set locale to %s; using Pootle default', lang) set_pootle_locale_from_settings()
def set_pootle_locale_from_settings(): """Try to set Pootle locale based on the language specified in settings.""" # See above for the reasoning why we need to skip setting locale under # Windows if os.name == 'nt': return lang = translation.to_locale(settings.LANGUAGE_CODE) try: if lang == 'tr' or lang.startswith('tr_'): raise ValueError("Turkish locale broken due to changed meaning of " "lower()") locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('Failed to set locale to Pootle default (%s); loading ' 'system default', lang) locale.setlocale(locale.LC_ALL, '')
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return FalseoutputPoin ## ===================================================================================
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() #PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2) return "???" ## ===================================================================================
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return "" ## =================================================================================== ## MAIN
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2) return False ## ===================================================================================
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return False ## =================================================================================== ## ====================================== Main Body ================================== # Import modules
def Number_Format(num, places=0, bCommas=True): # returns a formatted number according to current locality and given places # commas will be inserted if bCommas is True # returns the input num if error is raised try: #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return num ## ===================================================================================
def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() return "" ## ===================================================================================
def next_time(self, evt): locale.setlocale(locale.LC_ALL, 'en_US.UTF8') dt_str = str(self.result.stdout)[2:][:-3] last_date = datetime.datetime.strptime(dt_str, '%a %b %d %H:%M %Y') hope_date = last_date + datetime.timedelta(hours=1) print('last_date : ', last_date) print('hope_date : ', hope_date) now = datetime.datetime.now() print('now : ', str(now)) if now > hope_date: print('backup needed') newlabel = 'auto backup now' self.next_item.set_label(newlabel) self.backup_t(evt) else: print('no backup needed') next = hope_date - now newlabel = 'next auto backup in about '+str(next)[:-10][2:]+' min' print(newlabel) self.next_item.set_label(newlabel) return 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 _check_locale(self): ''' Uses the locale module to test the currently set locale (per the LANG and LC_CTYPE environment settings) ''' try: # setting the locale to '' uses the default locale # as it would be returned by locale.getdefaultlocale() locale.setlocale(locale.LC_ALL, '') except locale.Error: # fallback to the 'C' locale, which may cause unicode # issues but is preferable to simply failing because # of an unknown locale locale.setlocale(locale.LC_ALL, 'C') os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' os.environ['LC_MESSAGES'] = 'C' except Exception: e = get_exception() self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % e)
def set_default_encoding(): try: locale.setlocale(locale.LC_ALL, '') except: print ('WARNING: Failed to set default libc locale, using en_US.UTF-8') locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') try: enc = locale.getdefaultlocale()[1] except Exception: enc = None if not enc: enc = locale.nl_langinfo(locale.CODESET) if not enc or enc.lower() == 'ascii': enc = 'UTF-8' try: enc = codecs.lookup(enc).name except LookupError: enc = 'UTF-8' sys.setdefaultencoding(enc) del sys.setdefaultencoding
def __init__(self, configo, path): #lib_dir = os.path.abspath(os.path.dirname(sys.argv[0])) self.locale_dir = unival(os.path.join(path, 'locale/')) if 'LC_MESSAGES' in vars(locale): # linux locale.setlocale(locale.LC_MESSAGES, '') else: # windows locale.setlocale(locale.LC_ALL, '') # locale.setlocale(locale.LC_MESSAGES, '') # use user's preferred locale self.config = configo self.alphabet_26 = ["en_GB", "en_US", "pt_PT"] self.def_imported = False self.trans = dict() self.lang_titles = self.config.lang_titles self.all_lng = self.config.all_lng self.ok_lng = self.config.ok_lng
def number_to_day(self, day_number): """Returns localized day name by its CRON number Args: day_number: Number of a day Returns: Day corresponding to day_number Raises: IndexError: When day_number is not found """ # ADE force locale first... import locale locale.setlocale(locale.LC_ALL, '') return [ calendar.day_name[6], calendar.day_name[0], calendar.day_name[1], calendar.day_name[2], calendar.day_name[3], calendar.day_name[4], calendar.day_name[5] ][day_number]
def test_option_locale(self): self.assertFailure('-L') self.assertFailure('--locale') self.assertFailure('-L', 'en') lang, enc = locale.getdefaultlocale() lang = lang or 'C' enc = enc or 'UTF-8' try: oldlocale = locale.getlocale(locale.LC_TIME) try: locale.setlocale(locale.LC_TIME, (lang, enc)) finally: locale.setlocale(locale.LC_TIME, oldlocale) except (locale.Error, ValueError): self.skipTest('cannot set the system default locale') stdout = self.run_ok('--locale', lang, '--encoding', enc, '2004') self.assertIn('2004'.encode(enc), stdout)
def test_locale_caching(self): # Issue #22410 oldlocale = locale.setlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) for loc in 'en_US.iso88591', 'en_US.utf8': try: locale.setlocale(locale.LC_CTYPE, loc) except locale.Error: # Unsupported locale on this system self.skipTest('test needs %s locale' % loc) re.purge() self.check_en_US_iso88591() self.check_en_US_utf8() re.purge() self.check_en_US_utf8() self.check_en_US_iso88591()
def __enter__(self): # Default delay when pressing ESC is too long, at 1000ms os.environ["ESCDELAY"] = "25" self.pairs = Pairs() # Make curses use unicode locale.setlocale(locale.LC_ALL, "") self.screen = curses.initscr() curses.noecho() # Using raw instead of cbreak() gives us access to CTRL+C and others curses.raw() self.screen.keypad(True) if not self.blocking_events: self.screen.timeout(33) curses.start_color() curses.use_default_colors() self.hide_cursor() return self
def to_datetime(value, format, locale=None): """Returns a datetime parsed from value with the specified format and locale. If no year is specified in the parsing format it is taken from the current date. """ if locale: old_locale = localelib.getlocale(localelib.LC_TIME) localelib.setlocale(localelib.LC_TIME, locale) time_s = time.strptime(value, format) dt = datetime.datetime(*time_s[0:5]) # 1900 is the default year from strptime, means no year parsed if dt.year == 1900: dt = dt.replace(year=datetime.datetime.utcnow().year) if locale: localelib.setlocale(localelib.LC_TIME, old_locale) return dt
def __init__(self, brain=None): """ Load a GUI in a shell console for testing TTS, STT and brain configuration :param brain: The Brain object provided by the brain.yml :type brain: Brain .. seealso:: Brain """ # override brain self.brain = brain # get settings sl = SettingLoader() self.settings = sl.settings locale.setlocale(locale.LC_ALL, '') self.d = Dialog(dialog="dialog") self.d.set_background_title("Kalliope shell UI") self.show_main_menu()
def test_locale(self): try: oldloc = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, '') except locale.Error as err: self.skipTest("Cannot set locale: {}".format(err)) try: localeconv = locale.localeconv() sep = localeconv['thousands_sep'] point = localeconv['decimal_point'] text = format(123456789, "n") self.assertIn(sep, text) self.assertEqual(text.replace(sep, ''), '123456789') text = format(1234.5, "n") self.assertIn(sep, text) self.assertIn(point, text) self.assertEqual(text.replace(sep, ''), '1234' + point + '5') finally: locale.setlocale(locale.LC_ALL, oldloc)
def main(args=None): if args is None: args = sys.argv[1:] # Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger() autocomplete() try: cmd_name, cmd_args = parseopts(args) except PipError as exc: sys.stderr.write("ERROR: %s" % exc) sys.stderr.write(os.linesep) sys.exit(1) # Needed for locale.getpreferredencoding(False) to work # in pip.utils.encoding.auto_decode try: locale.setlocale(locale.LC_ALL, '') except locale.Error as e: # setlocale can apparently crash if locale are uninitialized logger.debug("Ignoring error %s when setting locale", e) command = commands_dict[cmd_name](isolated=check_isolated(cmd_args)) return command.main(cmd_args) # ########################################################### # # Writing freeze files
def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale)
def __exit__(self, *args): _locale.setlocale(_locale.LC_TIME, self.oldlocale)
def datetimeToRFC1123(digits14): currentOS = platform.system() if currentOS == 'Darwin': newLocale = 'en_US' elif currentOS == 'Windows': newLocale = 'english' else: # Assume Linux newLocale = 'en_US.utf8' locale.setlocale(locale.LC_TIME, newLocale) d = datetime.datetime.strptime(digits14, '%Y%m%d%H%M%S') return d.strftime('%a, %d %b %Y %H:%M:%S GMT')
def main(): # import all locales locale.setlocale(locale.LC_ALL, '') # ---- configuration --- conf = get_user_config() bar = conf['bar'] main_loop(bar)
def editor(**kwargs): os.environ['ESCDELAY'] = '25' if sys.version_info.major < 3: lc_all = locale.getlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, '') else: lc_all = None try: return curses.wrapper(main, **kwargs) finally: if lc_all is not None: locale.setlocale(locale.LC_ALL, lc_all)
def format_price(self, price, symbol=True): try: locale.setlocale(locale.LC_ALL, "en_GB") pricetext = None if symbol: pricetext = locale.currency((price/100.0)).replace("\xa3","£") else: pricetext = locale.currency((price/100.0)).replace("\xa3","") # Strip all non-ascii characters pricetext = "".join(i for i in pricetext if ord(i)<128) return pricetext except Exception: return "-"
def format_price(self, price, symbol=True): locale.setlocale(locale.LC_ALL, "en_GB") pricetext = None if symbol: pricetext = locale.currency((price/100.0)) else: pricetext = locale.currency((price/100.0)).replace("\xa3","") # Return the price formatted decoded = None try: decoded = pricetext.decode("utf-8") except Exception: decoded = pricetext.decode("latin-1") return decoded
def locale_strftime(lang): time_locale = { '%a': [], '%A': [], '%b': [None], '%B': [None], '%p': [], } encoding = locale.getdefaultlocale()[1] if not encoding: encoding = 'UTF-8' if encoding.lower() in ('utf', 'utf8'): encoding = 'UTF-8' if encoding == 'cp1252': encoding = '1252' if os.name == 'nt': lang = _LOCALE2WIN32.get(lang, lang) locale.setlocale(locale.LC_ALL, lang + '.' + encoding) t = list(time.gmtime()) for i in range(12): t[1] = i + 1 for format in ('%b', '%B'): time_locale[format].append(time.strftime(format, t).decode(encoding)) for i in range(7): t[6] = i for format in ('%a', '%A'): time_locale[format].append(time.strftime(format, t).decode(encoding)) t[3] = 0 time_locale['%p'].append(time.strftime('%p', t).decode(encoding)) t[3] = 23 time_locale['%p'].append(time.strftime('%p', t).decode(encoding)) return time_locale