当前位置: 首页>>代码示例>>Python>>正文


Python locale.nl_langinfo方法代码示例

本文整理汇总了Python中locale.nl_langinfo方法的典型用法代码示例。如果您正苦于以下问题:Python locale.nl_langinfo方法的具体用法?Python locale.nl_langinfo怎么用?Python locale.nl_langinfo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在locale的用法示例。


在下文中一共展示了locale.nl_langinfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_default_encoding

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def set_default_encoding():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        print ('WARNING: Failed to set default libc locale, using en_US.UTF-8')
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    try:
        enc = locale.getdefaultlocale()[1]
    except Exception:
        enc = None
    if not enc:
        enc = locale.nl_langinfo(locale.CODESET)
    if not enc or enc.lower() == 'ascii':
        enc = 'UTF-8'
    try:
        enc = codecs.lookup(enc).name
    except LookupError:
        enc = 'UTF-8'
    sys.setdefaultencoding(enc)
    del sys.setdefaultencoding 
开发者ID:kovidgoyal,项目名称:build-calibre,代码行数:22,代码来源:site.py

示例2: print_formatted

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def print_formatted(self, fp=sys.stdout, no_color=False,
                        show_cmd=False, show_user=False, show_pid=False,
                        gpuname_width=16,
                        ):
        # header
        time_format = locale.nl_langinfo(locale.D_T_FMT)
        header_msg = '{t.bold_white}{hostname}{t.normal}  {timestr}'.format(**{
            'hostname' : self.hostname,
            'timestr' : self.query_time.strftime(time_format),
            't' : term if not no_color \
                       else Terminal(force_styling=None)
        })

        fp.write(header_msg)
        fp.write('\n')

        # body
        gpuname_width = max([gpuname_width] + [len(g.entry['name']) for g in self])
        for g in self:
            g.print_to(fp,
                       with_colors=not no_color,
                       show_cmd=show_cmd,
                       show_user=show_user,
                       show_pid=show_pid,
                       gpuname_width=gpuname_width)
            fp.write('\n')

        fp.flush() 
开发者ID:Lyken17,项目名称:mxbox,代码行数:30,代码来源:gpustat.py

示例3: getLocaleDate

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def getLocaleDate():
    """Provides locale formatted date"""
    now = datetime.datetime.now()
    try:
        date_format = locale.nl_langinfo(locale.D_FMT)
        return now.strftime(date_format)
    except:
        return now.strftime('%Y-%m-%d') 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:10,代码来源:misc.py

示例4: getLocaleTime

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def getLocaleTime():
    """Provides locale formatted time"""
    now = datetime.datetime.now()
    try:
        time_format = locale.nl_langinfo(locale.T_FMT)
        return now.strftime(time_format)
    except:
        return now.strftime('%H:%M:%S') 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:10,代码来源:misc.py

示例5: _str_to_decimal

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def _str_to_decimal(num_str):
    radix = locale.nl_langinfo(locale.RADIXCHAR)
    if radix != '.':
        num_str = num_str.replace(radix, '.')

    return Decimal(num_str) 
开发者ID:storaged-project,项目名称:libbytesize,代码行数:8,代码来源:bytesize.py

示例6: testTrueDiv

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def testTrueDiv(self):
        x = SizeStruct.new_from_str("1024 B")
        y = SizeStruct.new_from_str("-102.4 B") # rounds to whole bytes
        divResult = float(x.true_div(y)[:15].replace(locale.nl_langinfo(locale.RADIXCHAR), ".")) # just some number to cover accurancy and not cross max float range
        self.assertAlmostEqual(divResult, 1024.0/-102.0)

        x = SizeStruct.new_from_str("1 MiB")
        y = SizeStruct.new_from_str("1 KiB")
        divResult = float(x.true_div(y)[:15].replace(locale.nl_langinfo(locale.RADIXCHAR), ".")) # just some number to cover accurancy and not cross max float range
        self.assertAlmostEqual(divResult, 1024.0)
    #enddef 
开发者ID:storaged-project,项目名称:libbytesize,代码行数:13,代码来源:libbytesize_unittest.py

示例7: set_logging

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def set_logging(name="atomic_reactor", level=logging.DEBUG, handler=None):
    # create logger
    logger = logging.getLogger(name)
    for hdlr in list(logger.handlers):  # make a copy so it doesn't change
        logger.removeHandler(hdlr)

    logger.setLevel(level)

    if not handler:
        # create console handler and set level to debug
        log_encoding = nl_langinfo(CODESET)
        encoded_stream = EncodedStream(sys.stderr.fileno(), log_encoding)
        handler = logging.StreamHandler(encoded_stream)
        handler.setLevel(logging.DEBUG)

        # create formatter
        formatter = ArchFormatter(ATOMIC_REACTOR_LOGGING_FMT)

        # add formatter to ch
        handler.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(handler)

    logger = logging.getLogger('osbs')
    for hdlr in list(logger.handlers):  # make a copy so it doesn't change
        hdlr.setFormatter(formatter) 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:29,代码来源:__init__.py

示例8: _getTerminalCharset

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def _getTerminalCharset():
    """
    Function used by getTerminalCharset() to get terminal charset.

    @see getTerminalCharset()
    """
    # (1) Try locale.getpreferredencoding()
    try:
        charset = locale.getpreferredencoding()
        if charset:
            return charset
    except (locale.Error, AttributeError):
        pass

    # (2) Try locale.nl_langinfo(CODESET)
    try:
        charset = locale.nl_langinfo(locale.CODESET)
        if charset:
            return charset
    except (locale.Error, AttributeError):
        pass

    # (3) Try sys.stdout.encoding
    if hasattr(sys.stdout, "encoding") and sys.stdout.encoding:
        return sys.stdout.encoding

    # (4) Otherwise, returns "ASCII"
    return "ASCII" 
开发者ID:Yukinoshita47,项目名称:Yuki-Chan-The-Auto-Pentest,代码行数:30,代码来源:i18n.py

示例9: getTerminalCharset

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def getTerminalCharset():
    """
    Guess terminal charset using differents tests:
    1. Try locale.getpreferredencoding()
    2. Try locale.nl_langinfo(CODESET)
    3. Try sys.stdout.encoding
    4. Otherwise, returns "ASCII"

    WARNING: Call initLocale() before calling this function.
    """
    try:
        return getTerminalCharset.value
    except AttributeError:
        getTerminalCharset.value = _getTerminalCharset()
        return getTerminalCharset.value 
开发者ID:Yukinoshita47,项目名称:Yuki-Chan-The-Auto-Pentest,代码行数:17,代码来源:i18n.py

示例10: to_readable_string

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def to_readable_string(self):
        """ Return nice representation of date.

        Fuzzy dates => localized version
        Close dates => Today, Tomorrow, In X days
        Other => with locale dateformat, stripping year for this year
        """
        if self._fuzzy is not None:
            return STRINGS[self._fuzzy]

        days_left = self.days_left()
        if days_left == 0:
            return _('Today')
        elif days_left < 0:
            abs_days = abs(days_left)
            return ngettext('Yesterday', '%(days)d days ago', abs_days) % \
                {'days': abs_days}
        elif days_left > 0 and days_left <= 15:
            return ngettext('Tomorrow', 'In %(days)d days', days_left) % \
                {'days': days_left}
        else:
            locale_format = locale.nl_langinfo(locale.D_FMT)
            if calendar.isleap(datetime.date.today().year):
                year_len = 366
            else:
                year_len = 365
            if float(days_left) / year_len < 1.0:
                # if it's in less than a year, don't show the year field
                locale_format = locale_format.replace('/%Y', '')
                locale_format = locale_format.replace('.%Y', '.')
            return self._real_date.strftime(locale_format) 
开发者ID:getting-things-gnome,项目名称:gtg,代码行数:33,代码来源:dates.py

示例11: stats

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def stats(self):
        """Prints a nicely formatted list of statistics about the package"""

        self.downloads  # explicitly call, so we have first/last upload data
        fmt = locale.nl_langinfo(locale.D_T_FMT)
        sep = lambda s: locale.format('%d', s, 3)
        val = lambda dt: dt and dt.strftime(fmt) or '--'

        params = (
            self.package_name,
            val(self.first_upload),
            self.first_upload_rel,
            val(self.last_upload),
            self.last_upload_rel,
            sep(len(self.releases)),
            sep(self.max()),
            sep(self.min()),
            sep(self.average()),
            sep(self.total()),
        )

        print("""PyPI Package statistics for: %s
              First Upload: %40s (%s)
              Last Upload:  %40s (%s)
              Number of releases: %34s
              Most downloads:    %35s
              Fewest downloads:  %35s
              Average downloads: %35s
              Total downloads:   %35s
              """ % params) 
开发者ID:SanPen,项目名称:GridCal,代码行数:32,代码来源:download_stats.py

示例12: format_date

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def format_date(loc, d):
    with switchlocale(loc):
        fmt = locale.nl_langinfo(locale.D_T_FMT)
        return d.strftime(fmt) 
开发者ID:PacktPublishing,项目名称:Modern-Python-Standard-Library-Cookbook,代码行数:6,代码来源:datetimes_05.py

示例13: guess_encoding

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def guess_encoding(data):
    """
    Given a byte string, attempt to decode it.
    Tries the standard 'UTF8' and 'latin-1' encodings,
    Plus several gathered from locale information.

    The calling program *must* first call::

        locale.setlocale(locale.LC_ALL, '')

    If successful it returns ``(decoded_unicode, successful_encoding)``.
    If unsuccessful it raises a ``UnicodeError``.
    """
    successful_encoding = None
    # we make 'utf-8' the first encoding
    encodings = ['utf-8']
    #
    # next we add anything we can learn from the locale
    try:
        encodings.append(locale.nl_langinfo(locale.CODESET))
    except AttributeError:
        pass
    try:
        encodings.append(locale.getlocale()[1])
    except (AttributeError, IndexError):
        pass
    try:
        encodings.append(locale.getdefaultlocale()[1])
    except (AttributeError, IndexError):
        pass
    #
    # we try 'latin-1' last
    encodings.append('latin-1')
    for enc in encodings:
        # some of the locale calls
        # may have returned None
        if not enc:
            continue
        try:
            decoded = text_type(data, enc)
            successful_encoding = enc

        except (UnicodeError, LookupError):
            pass
        else:
            break
    if not successful_encoding:
         raise UnicodeError(
        'Unable to decode input data.  Tried the following encodings: %s.'
        % ', '.join([repr(enc) for enc in encodings if enc]))
    else:
         return (decoded, successful_encoding)


##########################################################################
# Remove repeated elements from a list deterministcally
########################################################################## 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:59,代码来源:util.py

示例14: test

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def test():
    """Simple test program."""
    root = Tk()
    root.withdraw()
    fd = LoadFileDialog(root)
    loadfile = fd.go(key="test")
    fd = SaveFileDialog(root)
    savefile = fd.go(key="test")
    print(loadfile, savefile)

    # Since the file name may contain non-ASCII characters, we need
    # to find an encoding that likely supports the file name, and
    # displays correctly on the terminal.

    # Start off with UTF-8
    enc = "utf-8"
    import sys

    # See whether CODESET is defined
    try:
        import locale
        locale.setlocale(locale.LC_ALL,'')
        enc = locale.nl_langinfo(locale.CODESET)
    except (ImportError, AttributeError):
        pass

    # dialog for openening files

    openfilename=askopenfilename(filetypes=[("all files", "*")])
    try:
        fp=open(openfilename,"r")
        fp.close()
    except:
        print("Could not open File: ")
        print(sys.exc_info()[1])

    print("open", openfilename.encode(enc))

    # dialog for saving files

    saveasfilename=asksaveasfilename()
    print("saveas", saveasfilename.encode(enc)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:44,代码来源:filedialog.py

示例15: guess_encoding

# 需要导入模块: import locale [as 别名]
# 或者: from locale import nl_langinfo [as 别名]
def guess_encoding(data):
    """
    Given a byte string, attempt to decode it.
    Tries the standard 'UTF8' and 'latin-1' encodings,
    Plus several gathered from locale information.

    The calling program *must* first call::

        locale.setlocale(locale.LC_ALL, '')

    If successful it returns ``(decoded_unicode, successful_encoding)``.
    If unsuccessful it raises a ``UnicodeError``.
    """
    successful_encoding = None
    # we make 'utf-8' the first encoding
    encodings = ['utf-8']
    #
    # next we add anything we can learn from the locale
    try:
        encodings.append(locale.nl_langinfo(locale.CODESET))
    except AttributeError:
        pass
    try:
        encodings.append(locale.getlocale()[1])
    except (AttributeError, IndexError):
        pass
    try:
        encodings.append(locale.getdefaultlocale()[1])
    except (AttributeError, IndexError):
        pass
    #
    # we try 'latin-1' last
    encodings.append('latin-1')
    for enc in encodings:
        # some of the locale calls
        # may have returned None
        if not enc:
            continue
        try:
            decoded = unicode(data, enc)
            successful_encoding = enc

        except (UnicodeError, LookupError):
            pass
        else:
            break
    if not successful_encoding:
         raise UnicodeError(
        'Unable to decode input data.  Tried the following encodings: %s.'
        % ', '.join([repr(enc) for enc in encodings if enc]))
    else:
         return (decoded, successful_encoding)


##########################################################################
# Invert a dictionary
########################################################################## 
开发者ID:blackye,项目名称:luscan-devel,代码行数:59,代码来源:util.py


注:本文中的locale.nl_langinfo方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。