我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用locale.Error()。
def _unsafe_writes(self, src, dest, exception): # sadly there are some situations where we cannot ensure atomicity, but only if # the user insists and we get the appropriate error we update the file unsafely if exception.errno == errno.EBUSY: #TODO: issue warning that this is an unsafe operation, but doing it cause user insists try: try: out_dest = open(dest, 'wb') in_src = open(src, 'rb') shutil.copyfileobj(in_src, out_dest) finally: # assuring closed files in 2.4 compatible way if out_dest: out_dest.close() if in_src: in_src.close() except (shutil.Error, OSError, IOError): e = get_exception() self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, e)) else: self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, exception))
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 _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 writefile(self, filename): self.fixlastline() text = self.text.get("1.0", "end-1c") if self.eol_convention != "\n": text = text.replace("\n", self.eol_convention) chars = self.encode(text) try: f = open(filename, "wb") f.write(chars) f.flush() f.close() return True except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False
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)
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_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_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 test_locale_calendars(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') self.assertIsInstance(local_weekday, str) self.assertIsInstance(local_month, str) 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) self.assertIsInstance(local_weekday, str) self.assertIsInstance(local_month, str) new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) self.assertEqual(old_october, new_october)
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 _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
def python_datetime_pretty_print(ts, lang): """ Pretty print of a locale :param ts: Timestamp :param lang: ui_locales :return: String """ formatter = '%d. %b.' if lang == 'de': try: locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') formatter = '%b. %Y' except locale.Error: locale.setlocale(locale.LC_TIME, 'en_US.UTF8') return datetime.strptime(str(ts), '%Y-%m-%d').strftime(formatter)
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 _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 as e: self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % to_native(e), exception=traceback.format_exc())
def _unsafe_writes(self, src, dest): # sadly there are some situations where we cannot ensure atomicity, but only if # the user insists and we get the appropriate error we update the file unsafely try: try: out_dest = open(dest, 'wb') in_src = open(src, 'rb') shutil.copyfileobj(in_src, out_dest) finally: # assuring closed files in 2.4 compatible way if out_dest: out_dest.close() if in_src: in_src.close() except (shutil.Error, OSError, IOError) as e: self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, to_native(e)), exception=traceback.format_exc())
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 determine_console_encoding(): try: #try for the preferred encoding encoding = locale.getpreferredencoding() #see if the locale.getdefaultlocale returns null #some versions of python\platforms return US-ASCII #when it cannot determine an encoding if not encoding or encoding == "US-ASCII": encoding = locale.getdefaultlocale()[1] if encoding: codecs.lookup(encoding) # make sure a lookup error is not made except (locale.Error, LookupError): encoding = None is_osx = sys.platform == "darwin" if not encoding: return ["US-ASCII", "utf-8"][is_osx] elif encoding.startswith("mac-") and is_osx: #certain versions of python would return mac-roman as default #OSX as a left over of earlier mac versions. return "utf-8" else: return encoding
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, str('en_US.UTF-8')) except locale.Error: try: locale.setlocale(locale.LC_ALL, str('English_United States.1252')) except locale.Error: warnings.warn( "Could not set locale to English/United States. " "Some date-related tests may fail") plt.switch_backend('Agg') # use Agg backend for these test if mpl.get_backend().lower() != "agg": msg = ("Using a wrong matplotlib backend ({0}), " "which will not produce proper images") raise Exception(msg.format(mpl.get_backend())) # These settings *must* be hardcoded for running the comparison # tests mpl.rcdefaults() # Start with all defaults mpl.rcParams['text.hinting'] = True mpl.rcParams['text.antialiased'] = True mpl.rcParams['text.hinting_factor'] = 8 # make sure we don't carry over bad plots from former tests msg = ("no of open figs: {} -> find the last test with ' " "python tests.py -v' and add a '@cleanup' decorator.") assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
def generate_sentence_date(self, date, granularity=0): """ Convert a date to a string, with an appropriate level of granularity. :param date: A datetime object. :param granularity: Granularity for the desired textual representation. 0: precise (date and time are returned) 1: day (only the week day is returned) 2: month (only year and month are returned) 3: year (only year is returned) :return: A textual representation of the date. """ full_locale = "{}.UTF-8".format(self.locale) try: # Careful, this operation is not thread safe ... locale.setlocale(locale.LC_TIME, full_locale) except locale.Error: print "Careful ! There was an error while trying to set the locale. This means your locale is not properly installed. Please refer to the README for more information." return "" if not date: return "" if granularity == 0: return date.strftime("%A") elif granularity == 1: return date.strftime("%A %-d") elif granularity == 2: return date.strftime("%A %-d %B") return date.strftime("%A %-d %B, %H:%M%p")
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 Number_Format(num, places=0, bCommas=True): # Format a number according to locality and given places import locale try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication except locale.Error: locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows) try: import locale 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 ## ===================================================================================