Python locale.nl_langinfo() Examples
The following are 22
code examples of locale.nl_langinfo().
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: site.py From build-calibre with GNU General Public License v3.0 | 6 votes |
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
Example #2
Source File: dates.py From gtg with GNU General Public License v3.0 | 5 votes |
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)
Example #3
Source File: datetimes_05.py From Modern-Python-Standard-Library-Cookbook with MIT License | 5 votes |
def format_date(loc, d): with switchlocale(loc): fmt = locale.nl_langinfo(locale.D_T_FMT) return d.strftime(fmt)
Example #4
Source File: download_stats.py From GridCal with GNU General Public License v3.0 | 5 votes |
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)
Example #5
Source File: i18n.py From EasY_HaCk with Apache License 2.0 | 5 votes |
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
Example #6
Source File: i18n.py From EasY_HaCk with Apache License 2.0 | 5 votes |
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"
Example #7
Source File: i18n.py From ITWSV with MIT License | 5 votes |
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
Example #8
Source File: i18n.py From ITWSV with MIT License | 5 votes |
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"
Example #9
Source File: i18n.py From Yuki-Chan-The-Auto-Pentest with MIT License | 5 votes |
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
Example #10
Source File: i18n.py From Yuki-Chan-The-Auto-Pentest with MIT License | 5 votes |
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"
Example #11
Source File: __init__.py From atomic-reactor with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #12
Source File: libbytesize_unittest.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
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
Example #13
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def _str_to_decimal(num_str): radix = locale.nl_langinfo(locale.RADIXCHAR) if radix != '.': num_str = num_str.replace(radix, '.') return Decimal(num_str)
Example #14
Source File: misc.py From codimension with GNU General Public License v3.0 | 5 votes |
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')
Example #15
Source File: misc.py From codimension with GNU General Public License v3.0 | 5 votes |
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')
Example #16
Source File: gpustat.py From mxbox with BSD 3-Clause "New" or "Revised" License | 5 votes |
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()
Example #17
Source File: util.py From razzy-spinner with GNU General Public License v3.0 | 4 votes |
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 ##########################################################################
Example #18
Source File: filedialog.py From Fluid-Designer with GNU General Public License v3.0 | 4 votes |
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))
Example #19
Source File: filedialog.py From ironpython3 with Apache License 2.0 | 4 votes |
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))
Example #20
Source File: util.py From luscan-devel with GNU General Public License v2.0 | 4 votes |
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 ##########################################################################
Example #21
Source File: filedialog.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 4 votes |
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))
Example #22
Source File: util.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 4 votes |
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 ##########################################################################