本文整理汇总了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
示例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()
示例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')
示例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')
示例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)
示例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
示例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)
示例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"
示例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
示例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)
示例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)
示例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)
示例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
##########################################################################
示例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))
示例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
##########################################################################