我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用locale.getdefaultlocale()。
def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init() if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if 0: # Enable to switch off string to Unicode coercion and implicit # Unicode to string conversion. encoding = "undefined" if encoding != "ascii": # On Non-Unicode builds this will raise an AttributeError... sys.setdefaultencoding(encoding) # Needs Python Unicode build !
def get_preferred_output_encoding(): '''Get encoding that should be used for printing strings .. warning:: Falls back to ASCII, so that output is most likely to be displayed correctly. ''' if hasattr(locale, 'LC_MESSAGES'): return ( locale.getlocale(locale.LC_MESSAGES)[1] or locale.getdefaultlocale()[1] or 'ascii' ) return ( locale.getdefaultlocale()[1] or 'ascii' )
def get_preferred_input_encoding(): '''Get encoding that should be used for reading shell command output .. warning:: Falls back to latin1 so that function is less likely to throw as decoded output is primary searched for ASCII values. ''' if hasattr(locale, 'LC_MESSAGES'): return ( locale.getlocale(locale.LC_MESSAGES)[1] or locale.getdefaultlocale()[1] or 'latin1' ) return ( locale.getdefaultlocale()[1] or 'latin1' )
def encodingFromContents( contents ): if( len(contents) > len(codecs.BOM_UTF8) and contents[0:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8 ): encoding = 'utf-8' elif( len(contents) > len(codecs.BOM_UTF16_LE) and contents[0:len(codecs.BOM_UTF16_LE)] in [codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE]): encoding = 'utf-16' elif( len(contents) > len(codecs.BOM_UTF32_LE) and contents[0:len(codecs.BOM_UTF32_LE)] in [codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE]): encoding = 'utf-32' else: encoding = locale.getdefaultlocale()[1] # Mac says mac-roman when utf-8 is what is required if encoding == 'mac-roman': encoding = 'utf-8' if encoding is None: encoding = 'iso8859-1' return encoding
def _initialize_(self, do_connect): self.pool_size = 0 super(SQLite, self)._initialize_(do_connect) path_encoding = sys.getfilesystemencoding() \ or locale.getdefaultlocale()[1] or 'utf8' if ':memory' in self.uri.split('://', 1)[0]: self.dbpath = ':memory:' else: self.dbpath = self.uri.split('://', 1)[1] if self.dbpath[0] != '/': if PY2: self.dbpath = pjoin( self.folder.decode(path_encoding).encode('utf8'), self.dbpath) else: self.dbpath = pjoin(self.folder, self.dbpath) if 'check_same_thread' not in self.driver_args: self.driver_args['check_same_thread'] = False if 'detect_types' not in self.driver_args and do_connect: self.driver_args['detect_types'] = self.driver.PARSE_DECLTYPES
def _translate_msgid(msgid, domain, desired_locale=None): if not desired_locale: system_locale = locale.getdefaultlocale() # If the system locale is not available to the runtime use English if not system_locale[0]: desired_locale = 'en_US' else: desired_locale = system_locale[0] locale_dir = os.environ.get(domain.upper() + '_LOCALEDIR') lang = gettext.translation(domain, localedir=locale_dir, languages=[desired_locale], fallback=True) if six.PY3: translator = lang.gettext else: translator = lang.ugettext translated_message = translator(msgid) return translated_message
def test_type(): import locale _, encoding = locale.getdefaultlocale() buf = '' while True: ch = getchar() if ch == '\x03': # Ctrl+C break buf += ch try: text = buf.decode(encoding) except: pass else: print 'try to input', repr(text) if len(buf) == 1: service.keyboard(buf) else: service.type(text) buf = ''
def Start(): global DEBUGMODE # Switch to debug mode if needed debugFile = Core.storage.join_path(Core.app_support_path, Core.config.bundles_dir_name, NAME + '.bundle', 'debug') DEBUGMODE = os.path.isfile(debugFile) if DEBUGMODE: version = VERSION + ' ****** WARNING Debug mode on *********' print("******** Started %s on %s at %s with locale set to %s **********" %(NAME + ' V' + version, Platform.OS, time.strftime("%Y-%m-%d %H:%M"), locale.getdefaultlocale())) else: version = VERSION Log.Debug("******* Started %s on %s at %s with locale set to %s ***********" %(NAME + ' V' + version, Platform.OS, time.strftime("%Y-%m-%d %H:%M"), locale.getdefaultlocale())) Plugin.AddViewGroup('List', viewMode='List', mediaType='items') Plugin.AddViewGroup("Details", viewMode="InfoList", mediaType="items") ObjectContainer.art = R(ART) ObjectContainer.title1 = NAME + VERSION DirectoryObject.thumb = R(ICON) HTTP.CacheTime = 0 Log.Debug('Misc module is version: %s' %misc.getVersion()) #################################################################################################### # Main menu ####################################################################################################
def date_time_str(t): """Convert seconds since the Epoch to formatted local date and time strings.""" source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH') if source_date_epoch is not None: t = time.gmtime(min(t, int(source_date_epoch))) else: t = time.localtime(t) date_str = time.strftime('%Y-%m-%d',t) time_str = time.strftime('%H:%M:%S',t) if source_date_epoch is not None: time_str += ' UTC' elif time.daylight and t.tm_isdst == 1: time_str += ' ' + time.tzname[1] else: time_str += ' ' + time.tzname[0] # Attempt to convert the localtime to the output encoding. try: time_str = char_encode(time_str.decode(locale.getdefaultlocale()[1])) except Exception: pass return date_str, time_str
def _check_locale(self): ''' Uses the locale module to test the currently set locale (per the LANG and LC_CTYPE environment settings) ''' try: # setting the locale to '' uses the default locale # as it would be returned by locale.getdefaultlocale() locale.setlocale(locale.LC_ALL, '') except locale.Error: # fallback to the 'C' locale, which may cause unicode # issues but is preferable to simply failing because # of an unknown locale locale.setlocale(locale.LC_ALL, 'C') os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' os.environ['LC_MESSAGES'] = 'C' except Exception: e = get_exception() self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % e)
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