Python源码示例:locale.setlocale()
示例1
def activate_locale(self):
"""
Activates this user's locale
"""
try:
lc = self.locale.split('.')
region = self.region.split('.')
locale.setlocale(locale.LC_TIME, region)
locale.setlocale(locale.LC_MESSAGES, lc)
locale.setlocale(locale.LC_NUMERIC, region)
locale.setlocale(locale.LC_MONETARY, region)
except Exception as e:
locale.setlocale(locale.LC_ALL, None)
# Return the language code
return self.locale.split('_', 1)[0]
示例2
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
示例3
def testConvertTo(self):
size = Size("1.5 KiB")
conv = size.convert_to("KiB")
self.assertEqual(conv, Decimal("1.5"))
locale.setlocale(locale.LC_ALL,'cs_CZ.UTF-8')
size = Size("1.5 KiB")
conv = size.convert_to("KiB")
self.assertEqual(conv, Decimal("1.5"))
# this persian locale uses a two-byte unicode character for the radix
locale.setlocale(locale.LC_ALL, 'ps_AF.UTF-8')
size = Size("1.5 KiB")
conv = size.convert_to("KiB")
self.assertEqual(conv, Decimal("1.5"))
locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
示例4
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)
示例5
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())
示例6
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()
示例7
def tick(self):
with setlocale(ui_locale):
if time_format == 12:
time2 = time.strftime('%I:%M %p') #hour in 12h format
else:
time2 = time.strftime('%H:%M') #hour in 24h format
day_of_week2 = time.strftime('%A')
date2 = time.strftime(date_format)
# if time string has changed, update it
if time2 != self.time1:
self.time1 = time2
self.timeLbl.config(text=time2)
if day_of_week2 != self.day_of_week1:
self.day_of_week1 = day_of_week2
self.dayOWLbl.config(text=day_of_week2)
if date2 != self.date1:
self.date1 = date2
self.dateLbl.config(text=date2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
self.timeLbl.after(200, self.tick)
示例8
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)
示例9
def save_preferences(self):
language = self.ui.get_language()
if language == None:
language = ''
self.check_permissions_dialog = self.ui.get_check_permissions()
check_permissions = '1' if self.check_permissions_dialog else '0'
config = configparser.ConfigParser()
if language != '':
try:
locale.setlocale(locale.LC_ALL, (language, 'UTF-8'))
except locale.Error:
self.ui.info_dialog(_("Failed to change language."),
_("Make sure locale '" + str(language) + ".UTF8' is generated on your system" ))
self.ui.set_language(self.locale)
language = self.ui.get_language()
config['DEFAULT'] = {
'locale': language,
'check_permissions': check_permissions,
'button_config': ','.join(map(str, self.button_config)),
}
config_file = os.path.join(self.config_path, 'config.ini')
with open(config_file, 'w') as file:
config.write(file)
示例10
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)
示例11
def initLocale():
# Only initialize locale once
if initLocale.is_done:
return getTerminalCharset()
initLocale.is_done = True
# Setup locales
try:
locale.setlocale(locale.LC_ALL, "")
except (locale.Error, IOError):
pass
# Get the terminal charset
charset = getTerminalCharset()
# UnicodeStdout conflicts with the readline module
if config.unicode_stdout and ('readline' not in sys.modules):
# Replace stdout and stderr by unicode objet supporting unicode string
sys.stdout = UnicodeStdout(sys.stdout, charset)
sys.stderr = UnicodeStdout(sys.stderr, charset)
return charset
示例12
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)
示例13
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)
示例14
def initLocale():
# Only initialize locale once
if initLocale.is_done:
return getTerminalCharset()
initLocale.is_done = True
# Setup locales
try:
locale.setlocale(locale.LC_ALL, "")
except (locale.Error, IOError):
pass
# Get the terminal charset
charset = getTerminalCharset()
# UnicodeStdout conflicts with the readline module
if config.unicode_stdout and ('readline' not in sys.modules):
# Replace stdout and stderr by unicode objet supporting unicode string
sys.stdout = UnicodeStdout(sys.stdout, charset)
sys.stderr = UnicodeStdout(sys.stderr, charset)
return charset
示例15
def start(self, no_delay):
self.window = curses.initscr()
curses.start_color()
curses.use_default_colors()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
self.window.nodelay(no_delay)
self.init_colors()
self.window.bkgd(curses.color_pair(self.WHITE))
locale.setlocale(locale.LC_ALL, '') # set your locale
self.code = locale.getpreferredencoding()
示例16
def init_locale(request):
"""Initialize locale for the check-in interface."""
lc = settings.INSTALL_LOCALE.split('.')
locale.setlocale(locale.LC_TIME, lc)
locale.setlocale(locale.LC_NUMERIC, lc)
locale.setlocale(locale.LC_MESSAGES, lc)
locale.setlocale(locale.LC_MONETARY, lc)
translation.activate(settings.INSTALL_LANGUAGE)
request.session[translation.LANGUAGE_SESSION_KEY] = settings.INSTALL_LANGUAGE
示例17
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
示例18
def run_with_locale(catstr, *locales):
def decorator(func):
def inner(*args, **kwds):
try:
import locale
category = getattr(locale, catstr)
orig_locale = locale.setlocale(category)
except AttributeError:
# if the test author gives us an invalid category string
raise
except:
# cannot retrieve original locale, so do nothing
locale = orig_locale = None
else:
for loc in locales:
try:
locale.setlocale(category, loc)
break
except:
pass
# now run the function, resetting the locale on exceptions
try:
return func(*args, **kwds)
finally:
if locale and orig_locale:
locale.setlocale(category, orig_locale)
inner.__name__ = func.__name__
inner.__doc__ = func.__doc__
return inner
return decorator
#=======================================================================
# Decorator for running a function in a specific timezone, correctly
# resetting it afterwards.
示例19
def __enter__(self):
self.oldlocale = _locale.getlocale(_locale.LC_TIME)
_locale.setlocale(_locale.LC_TIME, self.locale)
示例20
def __exit__(self, *args):
_locale.setlocale(_locale.LC_TIME, self.oldlocale)
示例21
def run_with_locale(catstr, *locales):
def decorator(func):
def inner(*args, **kwds):
try:
import locale
category = getattr(locale, catstr)
orig_locale = locale.setlocale(category)
except AttributeError:
# if the test author gives us an invalid category string
raise
except:
# cannot retrieve original locale, so do nothing
locale = orig_locale = None
else:
for loc in locales:
try:
locale.setlocale(category, loc)
break
except:
pass
# now run the function, resetting the locale on exceptions
try:
return func(*args, **kwds)
finally:
if locale and orig_locale:
locale.setlocale(category, orig_locale)
inner.__name__ = func.__name__
inner.__doc__ = func.__doc__
return inner
return decorator
#=======================================================================
# Decorator for running a function in a specific timezone, correctly
# resetting it afterwards.
示例22
def updateDate( self ):
try:
locale.setlocale( locale.LC_ALL , 'en_US' )
except locale.Error:
locale.setlocale( locale.LC_ALL , 'us_us' )
except:
pass
self.date = datetime.datetime.now().strftime("%d-%b-%Y %H:%M:%S")
# Mark the object as deleted
示例23
def money(value):
locale.setlocale(locale.LC_ALL, '')
try:
if not value:
return locale.currency(0.0)
return locale.currency(value, symbol=True, grouping=True)
except ValueError:
locale.setlocale(locale.LC_MONETARY, 'en_US.utf8')
if not value:
return locale.currency(0.0)
return locale.currency(value, symbol=True, grouping=True)
示例24
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
示例25
def setup(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
示例26
def teardown(self):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
示例27
def __enter__(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
示例28
def __exit__(self, type, value, traceback):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
示例29
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)
示例30
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