我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用locale.getlocale()。
def get_preferred_output_encoding(): '''Get encoding that should be used for printing strings .. warning:: Falls back to ASCII, so that output is most likely to be displayed correctly. ''' if hasattr(locale, 'LC_MESSAGES'): return ( locale.getlocale(locale.LC_MESSAGES)[1] or locale.getdefaultlocale()[1] or 'ascii' ) return ( locale.getdefaultlocale()[1] or 'ascii' )
def get_preferred_input_encoding(): '''Get encoding that should be used for reading shell command output .. warning:: Falls back to latin1 so that function is less likely to throw as decoded output is primary searched for ASCII values. ''' if hasattr(locale, 'LC_MESSAGES'): return ( locale.getlocale(locale.LC_MESSAGES)[1] or locale.getdefaultlocale()[1] or 'latin1' ) return ( locale.getdefaultlocale()[1] or 'latin1' )
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 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 _GLXInfoToUnicode(string): """ Smart way to convert strings to unicode. This should give the expected result in most cases that are interesting for glxinfo output. """ # Try a number of popular encodings starting with the locale's default. # Try utf-8 before latin1, since latin1 will almost always succeed # but not necessarily be correct. lang, defenc = locale.getlocale(locale.LC_MESSAGES) if not defenc: encodings = ('utf-8', 'iso8859-1') else: encodings = (defenc, 'utf-8', 'iso8859-1') for encoding in encodings: try: return str(string, encoding, 'strict') except ValueError: continue # If we get here, all encodings failed. Use ascii with replacement # of illegal characters as a failsafe fallback. return str(string, 'ascii', 'replace')
def __init__(self, iface): QObject.__init__(self) self.iface = iface self.plugin_dir = os.path.dirname(__file__) self.__generate_action = None self.__export_action = None self.__importdata_action = None self.__configure_action = None self.__help_action = None self.__about_action = None self.__separator = None if locale.getlocale() == (None, None): locale.setlocale(locale.LC_ALL, '') # initialize translation qgis_locale = QLocale(QSettings().value('locale/userLocale')) locale_path = os.path.join(self.plugin_dir, 'i18n') self.translator = QTranslator() self.translator.load(qgis_locale, 'projectgenerator', '_', locale_path) QCoreApplication.installTranslator(self.translator) self.ili2db_configuration = BaseConfiguration() settings = QSettings() settings.beginGroup('QgsProjectGenerator/ili2db') self.ili2db_configuration.restore(settings)
def test_getsetlocale_issue1813(self): # Issue #1813: setting and getting the locale under a Turkish locale oldlocale = locale.getlocale() self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) for loc in ('tr_TR', 'tr_TR.UTF-8', 'tr_TR.ISO8859-9'): try: locale.setlocale(locale.LC_CTYPE, loc) break except locale.Error: continue else: # Unsupported locale on this system self.skipTest('test needs Turkish locale') loc = locale.getlocale() try: locale.setlocale(locale.LC_CTYPE, loc) except Exception as e: self.fail("Failed to set locale %r (default locale is %r): %r" % (loc, oldlocale, e)) self.assertEqual(loc, locale.getlocale())
def test_run_non_ascii_file(self): file = os.path.join(self.wd, 'non-ascii', 'utf-8') # Make sure the default localization conditions on this "system" # support UTF-8 encoding. loc = locale.getlocale() try: locale.setlocale(locale.LC_ALL, 'C.UTF-8') except locale.Error: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') sys.stdout, sys.stderr = StringIO(), StringIO() with self.assertRaises(SystemExit) as ctx: cli.run(('-f', 'parsable', file)) locale.setlocale(locale.LC_ALL, loc) self.assertEqual(ctx.exception.code, 0) out, err = sys.stdout.getvalue(), sys.stderr.getvalue() self.assertEqual(out, '') self.assertEqual(err, '')
def test_localeIndependent(self): """ The month name in the date is locale independent. """ # A point about three months in the past. then = self.now - (60 * 60 * 24 * 31 * 3) stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0)) # Fake that we're in a language where August is not Aug (e.g.: Spanish) currentLocale = locale.getlocale() locale.setlocale(locale.LC_ALL, "es_AR.UTF8") self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale) self.assertEqual( self._lsInTimezone('America/New_York', stat), '!--------- 0 0 0 0 Aug 28 17:33 foo') self.assertEqual( self._lsInTimezone('Pacific/Auckland', stat), '!--------- 0 0 0 0 Aug 29 09:33 foo') # If alternate locale is not available, the previous test will be # skipped, please install this locale for it to run
def _get_region_dumb(self): """ return dict estimate about the current countrycode/country """ res = {'countrycode': '', 'country': '', } try: # use LC_MONETARY as the best guess loc = locale.getlocale(locale.LC_MONETARY)[0] except Exception as e: LOG.warn("Failed to get locale: '%s'" % e) return res if not loc: return res countrycode = loc.split("_")[1] res["countrycode"] = countrycode res["country"] = get_region_name(countrycode) return res
def _execute(self, filename): # Create a MediaInfo handle handle = self.lib.MediaInfo_New() try: self.lib.MediaInfo_Option(handle, 'CharSet', 'UTF-8') # Fix for https://github.com/sbraz/pymediainfo/issues/22 # Python 2 does not change LC_CTYPE # at startup: https://bugs.python.org/issue6203 if sys.version_info < (3, ) and os.name == 'posix' and locale.getlocale() == (None, None): locale.setlocale(locale.LC_CTYPE, locale.getdefaultlocale()) self.lib.MediaInfo_Option(None, 'Inform', 'XML') self.lib.MediaInfo_Option(None, 'Complete', '1') self.lib.MediaInfo_Open(handle, filename) return self.lib.MediaInfo_Inform(handle, 0) finally: # Delete the handle self.lib.MediaInfo_Close(handle) self.lib.MediaInfo_Delete(handle)
def _getlang(): # Figure out what the current language is set to. return locale.getlocale(locale.LC_TIME)
def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale)
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 __init__(self, msg): """ :param msg ???????????????key?locale??? """ if isinstance(msg, types.DictType): country_code, _ = locale.getlocale(locale.LC_ALL) msg = msg[country_code] if isinstance(msg, unicode): super(GirlFriendException, self).__init__(msg.encode("utf-8")) self.msg = msg elif isinstance(msg, str): super(GirlFriendException, self).__init__(msg) self.msg = msg.decode("utf-8") else: raise TypeError
def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale) return _locale.getlocale(_locale.LC_TIME)[1]
def get_icu_locale(): try: return icu.Locale('.'.join(getlocale())) except TypeError: # pragma: no cover return icu.Locale()
def __init__(self): self.throw_exception_on_parse_error = True self.casing_type = CasingTypeEnum.Sentence self.verbose = False self.day_of_week_start_index_zero = True self.use_24hour_time_format = False code, encoding = locale.getlocale() self.locale_code = code self.use_24hour_time_format = code in [ "ru_RU", "uk_UA", "de_DE", "it_IT", "tr_TR", "cs_CZ"]
def in_foreign_locale(func): """ Swap LC_NUMERIC locale to one in which the decimal point is ',' and not '.' If not possible, raise SkipTest """ if sys.platform == 'win32': locales = ['FRENCH'] else: locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8'] def wrapper(*args, **kwargs): curloc = locale.getlocale(locale.LC_NUMERIC) try: for loc in locales: try: locale.setlocale(locale.LC_NUMERIC, loc) break except locale.Error: pass else: raise SkipTest("Skipping locale test, because " "French locale not found") return func(*args, **kwargs) finally: locale.setlocale(locale.LC_NUMERIC, locale=curloc) return nose.tools.make_decorator(func)(wrapper)
def get_default_language(default=None): """Determine the user's default language, if possible. This function uses the 'locale' module to try to determine the user's preferred language. The return value is as follows: * if a locale is available for the LC_MESSAGES category, that language is used * if a default locale is available, that language is used * if the keyword argument <default> is given, it is used * if nothing else works, None is returned Note that determining the user's language is in general only possible if they have set the necessary environment variables on their system. """ try: import locale tag = locale.getlocale()[0] if tag is None: tag = locale.getdefaultlocale()[0] if tag is None: raise Error("No default language available") return tag except Exception: pass return default
def test_basic(self): self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
def test_TimeRE_recreation(self): # The TimeRE instance should be recreated upon changing the locale. locale_info = locale.getlocale(locale.LC_TIME) try: locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8')) except locale.Error: return try: _strptime._strptime_time('10', '%d') # Get id of current cache object. first_time_re = _strptime._TimeRE_cache try: # Change the locale and force a recreation of the cache. locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8')) _strptime._strptime_time('10', '%d') # Get the new cache object's id. second_time_re = _strptime._TimeRE_cache # They should not be equal. self.assertIsNot(first_time_re, second_time_re) # Possible test locale is not supported while initial locale is. # If this is the case just suppress the exception and fall-through # to the resetting to the original locale. except locale.Error: pass # Make sure we don't trample on the locale setting once we leave the # test. finally: locale.setlocale(locale.LC_TIME, locale_info)
def test_getsetlocale_issue1813(self): # Issue #1813: setting and getting the locale under a Turkish locale oldlocale = locale.setlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) try: locale.setlocale(locale.LC_CTYPE, 'tr_TR') except locale.Error: # Unsupported locale on this system self.skipTest('test needs Turkish locale') loc = locale.getlocale(locale.LC_CTYPE) locale.setlocale(locale.LC_CTYPE, loc) self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
def openIRCLink(self, widget): host = socket.gethostname() user = getpass.getuser() lang = locale.getlocale()[0] self.openLink("http://ts.sch.gr/repo/irc?user=%s&host=%s&lang=%s" % \ (user, host, lang))
def test_lookup_issue1813(self): # Issue #1813: under Turkish locales, lookup of some codecs failed # because 'I' is lowercased as a dotless "i" oldlocale = locale.getlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) try: locale.setlocale(locale.LC_CTYPE, 'tr_TR') except locale.Error: # Unsupported locale on this system self.skipTest('test needs Turkish locale') c = codecs.lookup('ASCII') self.assertEqual(c.name, 'ascii')
def test_TimeRE_recreation_locale(self): # The TimeRE instance should be recreated upon changing the locale. locale_info = locale.getlocale(locale.LC_TIME) try: locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8')) except locale.Error: self.skipTest('test needs en_US.UTF8 locale') try: _strptime._strptime_time('10', '%d') # Get id of current cache object. first_time_re = _strptime._TimeRE_cache try: # Change the locale and force a recreation of the cache. locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8')) _strptime._strptime_time('10', '%d') # Get the new cache object's id. second_time_re = _strptime._TimeRE_cache # They should not be equal. self.assertIsNot(first_time_re, second_time_re) # Possible test locale is not supported while initial locale is. # If this is the case just suppress the exception and fall-through # to the resetting to the original locale. except locale.Error: self.skipTest('test needs de_DE.UTF8 locale') # Make sure we don't trample on the locale setting once we leave the # test. finally: locale.setlocale(locale.LC_TIME, locale_info)
def test_setlocale_unicode(self): oldlocale = locale.getlocale() self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) user_locale = locale.setlocale(locale.LC_CTYPE, '') unicode_locale = user_locale.decode('utf-8') user_locale2 = locale.setlocale(locale.LC_CTYPE, unicode_locale) self.assertEqual(user_locale, user_locale2)