當前位置: 首頁>>代碼示例>>Python>>正文


Python locale.Error方法代碼示例

本文整理匯總了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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:26,代碼來源:test_calendar.py

示例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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_calendar.py

示例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() 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_re.py

示例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) 
開發者ID:project-koku,項目名稱:koku,代碼行數:19,代碼來源:serializers.py

示例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) 
開發者ID:berarma,項目名稱:oversteer,代碼行數:25,代碼來源:gui.py

示例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) 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:27,代碼來源:__init__.py

示例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 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:22,代碼來源:testing.py

示例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 
開發者ID:Yukinoshita47,項目名稱:Yuki-Chan-The-Auto-Pentest,代碼行數:23,代碼來源:i18n.py

示例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) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:27,代碼來源:__init__.py

示例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() 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:26,代碼來源:__init__.py

示例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') 
開發者ID:DLR-RM,項目名稱:RAFCON,代碼行數:23,代碼來源:i18n.py

示例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 
開發者ID:pierluigiferrari,項目名稱:fcn8s_tensorflow,代碼行數:12,代碼來源:annotation.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:34,代碼來源:_locales.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:37,代碼來源:test_locale.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:28,代碼來源:testing.py


注:本文中的locale.Error方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。