Python源码示例:locale.getlocale()
示例1
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)
示例2
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())
示例3
def _currency_symbols():
"""Compile a list of valid currency symbols."""
current = locale.getlocale()
locales = list(locale.locale_alias.values())
symbols = set()
for loc in locales:
try:
locale.setlocale(locale.LC_MONETARY, locale.normalize(loc))
currency = "{int_curr_symbol}".format(**locale.localeconv())
if currency != "":
symbols.add(currency.strip())
except (locale.Error, UnicodeDecodeError):
continue
locale.setlocale(locale.LC_MONETARY, current)
return list(symbols)
示例4
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())
示例5
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
示例6
def __init__(self):
if os.path.isfile(os.path.dirname(os.path.abspath(__file__)) + '/keys/cert.crt') != True:
print("First run, generating certificate..")
execute_string = "openssl req -nodes -x509 -newkey rsa:4096 -keyout " + \
os.path.dirname(os.path.abspath(__file__)) + \
"/keys/key.pem -out " + os.path.dirname(os.path.abspath(__file__)) + \
"/keys/cert.crt -days 356 -subj " + \
"\"/C=AP/ST=Land/L=torc/O=AP Team/subjectAltName=IP:127.0.0.1\""
proc = Popen(execute_string, stdout=PIPE, stderr=PIPE, shell=True)
decode_locale = lambda s: s.decode(getlocale()[1])
self.tool_stdout, self.tool_stderr = map(decode_locale, proc.communicate())
# Callback / pause from here
return_code = proc.returncode
# Pong!
# curl -i http://127.0.0.1:5000/ping
示例7
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)
示例8
def get_unit_received(self):
"""
Returns (as a tuple) the GSX-compatible date and time of
when this unit was received
"""
import locale
langs = gsxws.get_format('en_XXX')
ts = self.unit_received_at
loc = locale.getlocale()
# reset locale to get correct AM/PM value
locale.setlocale(locale.LC_TIME, None)
result = ts.strftime(langs['df']), ts.strftime(langs['tf'])
locale.setlocale(locale.LC_TIME, loc)
return result
示例9
def _getlang():
# Figure out what the current language is set to.
return locale.getlocale(locale.LC_TIME)
示例10
def __enter__(self):
self.oldlocale = _locale.getlocale(_locale.LC_TIME)
_locale.setlocale(_locale.LC_TIME, self.locale)
示例11
def find_comma_decimal_point_locale():
"""See if platform has a decimal point as comma locale.
Find a locale that uses a comma instead of a period as the
decimal point.
Returns
-------
old_locale: str
Locale when the function was called.
new_locale: {str, None)
First French locale found, None if none found.
"""
if sys.platform == 'win32':
locales = ['FRENCH']
else:
locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8']
old_locale = locale.getlocale(locale.LC_NUMERIC)
new_locale = None
try:
for loc in locales:
try:
locale.setlocale(locale.LC_NUMERIC, loc)
new_locale = loc
break
except locale.Error:
pass
finally:
locale.setlocale(locale.LC_NUMERIC, locale=old_locale)
return old_locale, new_locale
示例12
def test_to_datetime_format_microsecond(self, cache):
# these are locale dependent
lang, _ = locale.getlocale()
month_abbr = calendar.month_abbr[4]
val = '01-{}-2011 00:00:01.978'.format(month_abbr)
format = '%d-%b-%Y %H:%M:%S.%f'
result = to_datetime(val, format=format, cache=cache)
exp = datetime.strptime(val, format)
assert result == exp
示例13
def test_can_set_locale_invalid_get(monkeypatch):
# see gh-22129
#
# In some cases, an invalid locale can be set,
# but a subsequent getlocale() raises a ValueError.
def mock_get_locale():
raise ValueError()
with monkeypatch.context() as m:
m.setattr(locale, "getlocale", mock_get_locale)
assert not tm.can_set_locale("")
示例14
def test_set_locale():
if com._all_none(_current_locale):
# Not sure why, but on some Travis runs with pytest,
# getlocale() returned (None, None).
pytest.skip("Current locale is not set.")
locale_override = os.environ.get("LOCALE_OVERRIDE", None)
if locale_override is None:
lang, enc = "it_CH", "UTF-8"
elif locale_override == "C":
lang, enc = "en_US", "ascii"
else:
lang, enc = locale_override.split(".")
enc = codecs.lookup(enc).name
new_locale = lang, enc
if not tm.can_set_locale(new_locale):
msg = "unsupported locale setting"
with pytest.raises(locale.Error, match=msg):
with tm.set_locale(new_locale):
pass
else:
with tm.set_locale(new_locale) as normalized_locale:
new_lang, new_enc = normalized_locale.split(".")
new_enc = codecs.lookup(enc).name
normalized_locale = new_lang, new_enc
assert normalized_locale == new_locale
# Once we exit the "with" statement, locale should be back to what it was.
current_locale = locale.getlocale()
assert current_locale == _current_locale
示例15
def set_locale(new_locale, lc_var=locale.LC_ALL):
"""Context manager for temporarily setting a locale.
Parameters
----------
new_locale : str or tuple
A string of the form <language_country>.<encoding>. For example to set
the current locale to US English with a UTF8 encoding, you would pass
"en_US.UTF-8".
lc_var : int, default `locale.LC_ALL`
The category of the locale being set.
Notes
-----
This is useful when you want to run a particular block of code under a
particular locale, without globally setting the locale. This probably isn't
thread-safe.
"""
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
normalized_locale = locale.getlocale()
if com._all_not_none(*normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.setlocale(lc_var, current_locale)
示例16
def _skip_if_not_us_locale():
lang, _ = locale.getlocale()
if lang != 'en_US':
return True
示例17
def preferredLanguages(self):
if platform=='darwin':
return NSLocale.preferredLanguages()
elif platform=='win32':
def wszarray_to_list(array):
offset = 0
while offset < len(array):
sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)
if sz:
yield sz
offset += len(sz)+1
else:
break
num = ctypes.c_ulong()
size = ctypes.c_ulong(0)
if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value):
buf = ctypes.create_unicode_buffer(size.value)
if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)):
return wszarray_to_list(buf)
return []
else: # POSIX
lang = locale.getlocale()[0]
return lang and [lang.replace('_','-')] or []
# singletons
示例18
def _getlang():
# Figure out what the current language is set to.
return locale.getlocale(locale.LC_TIME)
示例19
def __enter__(self):
self.oldlocale = _locale.getlocale(_locale.LC_TIME)
_locale.setlocale(_locale.LC_TIME, self.locale)
示例20
def _getlang():
# Figure out what the current language is set to.
return locale.getlocale(locale.LC_TIME)
示例21
def test_basic(self):
self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
示例22
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)
示例23
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')
示例24
def __enter__(self):
self.oldlocale = _locale.getlocale(_locale.LC_TIME)
_locale.setlocale(_locale.LC_TIME, self.locale)
return _locale.getlocale(_locale.LC_TIME)[1]
示例25
def test_get_set_locale(self):
import locale
locale.setlocale(locale.LC_ALL, 'en-US')
loc = locale.getlocale(locale.LC_ALL)
self.assertEqual(loc, ('en_US','ISO8859-1'))
locale.setlocale(locale.LC_ALL, 'C')
loc = locale.getlocale(locale.LC_ALL)
self.assertEqual(loc, (None,None))
self.assertTrue(locale.setlocale(locale.LC_ALL, '') != None)
if not is_posix: # TODO: figure this out
self.assertTrue(locale.getlocale() != None)
示例26
def test_turkish_upper_lower(self):
self.assertEqual(u"ı".upper(),u"I")
self.assertEqual(u"İ".lower(),u"i")
# as defined in http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt
PERFECT_UNICODE_CASING=False
import locale
lang,encoding = locale.getlocale()
if is_cli:
locale.setlocale(locale.LC_ALL, "tr_TR")
else:
locale.setlocale(locale.LC_ALL, "turkish")
if PERFECT_UNICODE_CASING:
self.assertEqual(u"I".lower(),u"ı")
self.assertEqual(u"i".upper(),u"İ")
else:
# cpython compatibility
self.assertEqual(u"I".lower(),u"i")
self.assertEqual(u"i".upper(),u"I")
locale.setlocale(locale.LC_ALL, (lang,encoding))
# Note:
# IronPython casing matches cpython implementation (linux and windows)
# In order to take advantage of better build-in unicode support in Windows
# ToUpper/ToLower can be called directly
if is_cli:
import System.Globalization.CultureInfo as CultureInfo
self.assertEqual(u"I".ToLower(CultureInfo("tr-TR")),u"ı")
self.assertEqual(u"i".ToUpper(CultureInfo("tr-TR")),u"İ")
示例27
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)
示例28
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)
示例29
def test_to_datetime_format_microsecond(self, cache):
# these are locale dependent
lang, _ = locale.getlocale()
month_abbr = calendar.month_abbr[4]
val = '01-{}-2011 00:00:01.978'.format(month_abbr)
format = '%d-%b-%Y %H:%M:%S.%f'
result = to_datetime(val, format=format, cache=cache)
exp = datetime.strptime(val, format)
assert result == exp
示例30
def setup_class(cls):
cls.locales = tm.get_locales()
cls.current_locale = locale.getlocale()
if not cls.locales:
pytest.skip("No locales found")