本文整理汇总了Python中locale.Error方法的典型用法代码示例。如果您正苦于以下问题:Python locale.Error方法的具体用法?Python locale.Error怎么用?Python locale.Error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类locale
的用法示例。
在下文中一共展示了locale.Error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_localecalendars
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
def test_localecalendars(self):
# ensure that Locale{Text,HTML}Calendar resets the locale properly
# (it is still not thread-safe though)
old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
try:
cal = calendar.LocaleTextCalendar(locale='')
local_weekday = cal.formatweekday(1, 10)
local_month = cal.formatmonthname(2010, 10, 10)
except locale.Error:
# cannot set the system default locale -- skip rest of test
raise unittest.SkipTest('cannot set the system default locale')
# should be encodable
local_weekday.encode('utf-8')
local_month.encode('utf-8')
self.assertEqual(len(local_weekday), 10)
self.assertGreaterEqual(len(local_month), 10)
cal = calendar.LocaleHTMLCalendar(locale='')
local_weekday = cal.formatweekday(1)
local_month = cal.formatmonthname(2010, 10)
# should be encodable
local_weekday.encode('utf-8')
local_month.encode('utf-8')
new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
self.assertEqual(old_october, new_october)
示例2: test_option_locale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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)
示例3: test_locale_caching
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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()
示例4: _currency_symbols
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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)
示例5: save_preferences
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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)
示例6: main
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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)
示例7: _can_set_locale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
def _can_set_locale(lc):
"""Check to see if we can set a locale without throwing an exception.
Parameters
----------
lc : str
The locale to attempt to set.
Returns
-------
isvalid : bool
Whether the passed locale can be set
"""
try:
with set_locale(lc):
pass
except locale.Error: # horrible name for a Exception subclass
return False
else:
return True
示例8: initLocale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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
示例9: main
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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 = parse_command(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=("--isolated" in cmd_args))
return command.main(cmd_args)
示例10: setup
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
def setup():
# The baseline images are created in this locale, so we should use
# it during all of the tests.
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except locale.Error:
try:
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
except locale.Error:
warnings.warn(
"Could not set locale to English/United States. "
"Some date-related tests may fail.")
mpl.use('Agg', force=True, warn=False) # use Agg backend for these tests
with warnings.catch_warnings():
warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
mpl.rcdefaults() # Start with all defaults
# These settings *must* be hardcoded for running the comparison tests and
# are not necessarily the default values as specified in rcsetup.py.
set_font_settings_for_testing()
set_reproducibility_for_testing()
示例11: setup_l10n
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
def setup_l10n(logger=None):
"""Setup RAFCON for localization
Specify the directory, where the translation files (*.mo) can be found (rafcon/locale/) and set localization domain
("rafcon").
:param logger: which logger to use for printing (either logging.log or distutils.log)
"""
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error as e:
logger and logger.warning("Cannot setup translations: {}".format(e))
localedir = resource_filename('rafcon', 'locale')
# Install gettext globally: Allows to use _("my string") without further imports
gettext.install('rafcon', localedir)
# Required for glade and the GtkBuilder
locale.bindtextdomain('rafcon', localedir)
locale.textdomain('rafcon')
示例12: updateDate
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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
示例13: find_comma_decimal_point_locale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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
示例14: test_set_locale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
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: can_set_locale
# 需要导入模块: import locale [as 别名]
# 或者: from locale import Error [as 别名]
def can_set_locale(lc, lc_var=locale.LC_ALL):
"""
Check to see if we can set a locale, and subsequently get the locale,
without raising an Exception.
Parameters
----------
lc : str
The locale to attempt to set.
lc_var : int, default `locale.LC_ALL`
The category of the locale being set.
Returns
-------
is_valid : bool
Whether the passed locale can be set
"""
try:
with set_locale(lc, lc_var=lc_var):
pass
except (ValueError,
locale.Error): # horrible name for a Exception subclass
return False
else:
return True