Python locale.setlocale() Examples

The following are 30 code examples of locale.setlocale(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module locale , or try the search function .
Example #1
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
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] 
Example #2
Source File: test_re.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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() 
Example #3
Source File: i18n.py    From ITWSV with MIT License 6 votes vote down vote up
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 
Example #4
Source File: lbs_py_override_unittest.py    From libbytesize with GNU Lesser General Public License v2.1 6 votes vote down vote up
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') 
Example #5
Source File: __init__.py    From FuYiSpider with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: __init__.py    From FuYiSpider with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: i18n.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
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 
Example #8
Source File: smartmirror.py    From Smart-Mirror with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: test_calendar.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #10
Source File: test_locale.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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()) 
Example #11
Source File: serializers.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #12
Source File: __init__.py    From jbox with MIT License 6 votes vote down vote up
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 
Example #13
Source File: __init__.py    From Python24 with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: gui.py    From oversteer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #15
Source File: main.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, formatter_class=argparse.HelpFormatter, prog=PROG):
        self.parser = argparse.ArgumentParser(
            prog=prog,
            description=DESCRIPTION,
            formatter_class=formatter_class,
        )
        self.build_parser = None
        self.bi_parser = None
        self.ib_parser = None
        self.source_types_parsers = None

        locale.setlocale(locale.LC_ALL, '') 
Example #16
Source File: test_re.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def check_en_US_iso88591(self):
        locale.setlocale(locale.LC_CTYPE, 'en_US.iso88591')
        self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
        self.assertTrue(re.match(b'\xc5', b'\xe5', re.L|re.I))
        self.assertTrue(re.match(b'\xe5', b'\xc5', re.L|re.I))
        self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
        self.assertTrue(re.match(b'(?Li)\xc5', b'\xe5'))
        self.assertTrue(re.match(b'(?Li)\xe5', b'\xc5')) 
Example #17
Source File: test_re.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def check_en_US_utf8(self):
        locale.setlocale(locale.LC_CTYPE, 'en_US.utf8')
        self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
        self.assertIsNone(re.match(b'\xc5', b'\xe5', re.L|re.I))
        self.assertIsNone(re.match(b'\xe5', b'\xc5', re.L|re.I))
        self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
        self.assertIsNone(re.match(b'(?Li)\xc5', b'\xe5'))
        self.assertIsNone(re.match(b'(?Li)\xe5', b'\xc5')) 
Example #18
Source File: testing.py    From vnpy_crypto with MIT License 5 votes vote down vote up
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".

    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)

        try:
            normalized_locale = locale.getlocale()
        except ValueError:
            yield new_locale
        else:
            if com._all_not_none(*normalized_locale):
                yield '.'.join(normalized_locale)
            else:
                yield new_locale
    finally:
        locale.setlocale(lc_var, current_locale) 
Example #19
Source File: extract_transaction.py    From pst-extraction with Apache License 2.0 5 votes vote down vote up
def run_regex_extraction(sample_text_str):

    # symbol usage:

    # locales=('en_AG', 'en_AU.utf8', 'en_BW.utf8', 'en_CA.utf8',
    #     'en_DK.utf8', 'en_GB.utf8', 'en_HK.utf8', 'en_IE.utf8', 'en_IN', 'en_NG',
    #     'en_NZ.utf8', 'en_PH.utf8', 'en_SG.utf8', 'en_US.utf8', 'en_ZA.utf8',
    #     'en_ZW.utf8')
    locales =('en_AG', 'en_AU.utf8', 'en_CA.utf8',
              'en_HK.utf8',
              'en_NZ.utf8', 'en_SG.utf8', 'en_US.utf8',
              'en_ZW.utf8')

    # for l in locales:
    #     locale.setlocale(locale.LC_ALL, l)
    #     conv=locale.localeconv()

    # print('{int_curr_symbol} ==> {currency_symbol}'.format(**conv))

    #     char_curr_sequence = conv['int_curr_symbol']
    #     currency_symbol = conv['currency_symbol']
    #
    #     print char_curr_sequence
    #     symbol = '$'
    #     trans_amount_l = scan_str_for_currency_symbols(symbol, sample_text_str)
    #     print trans_amount_l
    #
    # print sample_text_str

    symbol = '$'
    trans_amount_l = scan_str_for_currency_symbols(symbol, sample_text_str)
    print trans_amount_l
    return trans_amount_l

# Currently working regex (without spaces between $ and digits): 
Example #20
Source File: test_print.py    From vnpy_crypto with MIT License 5 votes vote down vote up
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) 
Example #21
Source File: test_ujson.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_encodeNonCLocale(self):
        import locale
        savedlocale = locale.getlocale(locale.LC_NUMERIC)
        try:
            locale.setlocale(locale.LC_NUMERIC, 'it_IT.UTF-8')
        except:
            try:
                locale.setlocale(locale.LC_NUMERIC, 'Italian_Italy')
            except:
                pytest.skip('Could not set locale for testing')
        assert ujson.loads(ujson.dumps(4.78e60)) == 4.78e60
        assert ujson.loads('4.78', precise_float=True) == 4.78
        locale.setlocale(locale.LC_NUMERIC, savedlocale) 
Example #22
Source File: smartmirror.py    From Smart-Mirror with MIT License 5 votes vote down vote up
def setlocale(name): #thread proof function to work with locale
    with LOCALE_LOCK:
        saved = locale.setlocale(locale.LC_ALL)
        try:
            yield locale.setlocale(locale.LC_ALL, name)
        finally:
            locale.setlocale(locale.LC_ALL, saved)

# maps open weather icons to
# icon reading is not impacted by the 'lang' parameter 
Example #23
Source File: test_locale.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #24
Source File: test_locale.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_setlocale_category(self):
        locale.setlocale(locale.LC_ALL)
        locale.setlocale(locale.LC_TIME)
        locale.setlocale(locale.LC_CTYPE)
        locale.setlocale(locale.LC_COLLATE)
        locale.setlocale(locale.LC_MONETARY)
        locale.setlocale(locale.LC_NUMERIC)

        # crasher from bug #7419
        self.assertRaises(locale.Error, locale.setlocale, 12345) 
Example #25
Source File: test_locale.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        locale.setlocale(self.locale_type, self.oldlocale) 
Example #26
Source File: test_locale.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.oldlocale = locale.setlocale(self.locale_type)
        locale.setlocale(self.locale_type, enUS_locale)
        if verbose:
            print "testing with \"%s\"..." % enUS_locale, 
Example #27
Source File: pickletester.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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.func_name = func.func_name
        inner.__doc__ = func.__doc__
        return inner
    return decorator 
Example #28
Source File: __init__.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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.func_name = func.func_name
        inner.__doc__ = func.__doc__
        return inner
    return decorator

#=======================================================================
# Decorator for running a function in a specific timezone, correctly
# resetting it afterwards. 
Example #29
Source File: test_strptime.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #30
Source File: test_strftime.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        try:
            import java
            java.util.Locale.setDefault(java.util.Locale.US)
        except ImportError:
            from locale import setlocale, LC_TIME
            saved_locale = setlocale(LC_TIME)
            setlocale(LC_TIME, 'C')
            self.addCleanup(setlocale, LC_TIME, saved_locale)