Python locale.getlocale() Examples

The following are 30 code examples of locale.getlocale(). 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: __init__.py    From torc with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #2
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 #3
Source File: test_calendar.py    From Fluid-Designer with GNU General Public License v3.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 #4
Source File: test_locale.py    From oss-ftp with MIT License 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 #5
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 #6
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 #7
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #8
Source File: test_strptime.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_TimeRE_recreation(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 #9
Source File: _locales.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
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 
Example #10
Source File: test_imap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_fetchInternalDateLocaleIndependent(self):
        """
        The month name in the date is locale independent.
        """
        # Fake that we're in a language where December is not Dec
        currentLocale = locale.setlocale(locale.LC_ALL, None)
        locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
        self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale)
        return self.testFetchInternalDate(1)

    # if alternate locale is not available, the previous test will be skipped,
    # please install this locale for it to run.  Avoid using locale.getlocale to
    # learn the current locale; its values don't round-trip well on all
    # platforms.  Fortunately setlocale returns a value which does round-trip
    # well. 
Example #11
Source File: _locales.py    From pySINDy with MIT License 5 votes vote down vote up
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 
Example #12
Source File: testing.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 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".
    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) 
Example #13
Source File: _test_decorators.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _skip_if_not_us_locale():
    lang, _ = locale.getlocale()
    if lang != 'en_US':
        return True 
Example #14
Source File: _strptime.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _getlang():
    # Figure out what the current language is set to.
    return locale.getlocale(locale.LC_TIME) 
Example #15
Source File: test_strptime.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) 
Example #16
Source File: calendar.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        self.oldlocale = _locale.getlocale(_locale.LC_TIME)
        _locale.setlocale(_locale.LC_TIME, self.locale) 
Example #17
Source File: repair.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #18
Source File: calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def __enter__(self):
        self.oldlocale = _locale.getlocale(_locale.LC_TIME)
        _locale.setlocale(_locale.LC_TIME, self.locale)
        return _locale.getlocale(_locale.LC_TIME)[1] 
Example #19
Source File: test_codecs.py    From oss-ftp with MIT License 5 votes vote down vote up
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') 
Example #20
Source File: test_strptime.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_TimeRE_recreation(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 #21
Source File: test_strptime.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_basic(self):
        self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) 
Example #22
Source File: _strptime.py    From oss-ftp with MIT License 5 votes vote down vote up
def _getlang():
    # Figure out what the current language is set to.
    return locale.getlocale(locale.LC_TIME) 
Example #23
Source File: gui.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def on_imi_help_live_chat_irc_activate(self, _widget):
        """Handle imi_help_live_chat_irc.activate event."""
        host = socket.gethostname()
        user = getpass.getuser()
        lang = locale.getlocale()[0]
        self.open_url("http://ts.sch.gr/repo/irc?user=%s&host=%s&lang=%s" %
                      (user, host, lang)) 
Example #24
Source File: testing.py    From Computable 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 all(lc is not None for lc in normalized_locale):
                yield '.'.join(normalized_locale)
            else:
                yield new_locale
    finally:
        locale.setlocale(lc_var, current_locale) 
Example #25
Source File: test_util.py    From Computable with MIT License 5 votes vote down vote up
def test_set_locale(self):
        if len(self.locales) == 1:
            raise nose.SkipTest("Only a single locale found, no point in "
                                "trying to test setting another locale")

        if LOCALE_OVERRIDE is not None:
            lang, enc = LOCALE_OVERRIDE.split('.')
        else:
            lang, enc = 'it_CH', 'UTF-8'

        enc = codecs.lookup(enc).name
        new_locale = lang, enc

        if not tm._can_set_locale(new_locale):
            with tm.assertRaises(locale.Error):
                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
                self.assertEqual(normalized_locale, new_locale)

        current_locale = locale.getlocale()
        self.assertEqual(current_locale, CURRENT_LOCALE) 
Example #26
Source File: test_timeseries.py    From Computable with MIT License 5 votes vote down vote up
def _skip_if_has_locale():
    import locale
    lang, _ = locale.getlocale()
    if lang is not None:
        raise nose.SkipTest("Specific locale is set {0}".format(lang)) 
Example #27
Source File: _strptime.py    From Computable with MIT License 5 votes vote down vote up
def _getlang():
    # Figure out what the current language is set to.
    return locale.getlocale(locale.LC_TIME) 
Example #28
Source File: test_print.py    From Computable 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 nose.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 nose.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 #29
Source File: test_codecs.py    From BinderFilter with MIT License 5 votes vote down vote up
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') 
Example #30
Source File: test_locale.py    From BinderFilter with MIT License 5 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)
        try:
            locale.setlocale(locale.LC_CTYPE, 'tr_TR')
        except locale.Error:
            # Unsupported locale on this system
            self.skipTest('test needs Turkish locale')
        loc = locale.getlocale()
        locale.setlocale(locale.LC_CTYPE, loc)
        self.assertEqual(loc, locale.getlocale())