Python locale.getdefaultlocale() Examples

The following are 30 code examples of locale.getdefaultlocale(). 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 kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 ! 
Example #2
Source File: site.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == "win32":
        import locale, codecs

        enc = locale.getdefaultlocale()[1]
        if enc.startswith("cp"):  # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings

                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = "mbcs" 
Example #3
Source File: site.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
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 ! 
Example #4
Source File: site.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 ! 
Example #5
Source File: test_calendar.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: zdict.py    From zdict with GNU General Public License v3.0 6 votes vote down vote up
def user_set_encoding_and_is_utf8():
    # Check user's encoding settings
    try:
        (lang, enc) = getdefaultlocale()
    except ValueError:
        print("Didn't detect your LC_ALL environment variable.")
        print("Please export LC_ALL with some UTF-8 encoding.")
        print("For example: `export LC_ALL=en_US.UTF-8`")
        return False
    else:
        if enc != "UTF-8":
            print("zdict only works with encoding=UTF-8, ")
            print("but your encoding is: {} {}".format(lang, enc))
            print("Please export LC_ALL with some UTF-8 encoding.")
            print("For example: `export LC_ALL=en_US.UTF-8`")
            return False
    return True 
Example #7
Source File: site.py    From oss-ftp with MIT License 6 votes vote down vote up
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 ! 
Example #8
Source File: site.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 ! 
Example #9
Source File: language.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def configure(self, lang=None):
        """
        Configures the funcion "_" for translating the texts of Wapiti,
        this method loads the language indicated as parameter or if the
        parameter is not specified, it will take the default language
        of the operating system.
        """
        if lang is None:
            # if lang is not specified, default language is used
            defLocale = locale.getdefaultlocale()
            langCounty = defLocale[0]   # en_UK
            lang = langCounty[:2]  # en
        if lang not in self.AVAILABLE_LANGS:
            # if lang is not one of the supported languages, we use english
            print("Oups! No translations found for your language... Using english.")
            print("Please send your translations for improvements.")
            print("===============================================================")
            lang = 'en'
        lan = gettext.translation('wapiti',
                                  self.LANG_PATH,
                                  languages=[lang],
                                  codeset="UTF-8")
        lan.install(unicode=1)

        #funcion which translates
        def _(key):
            return lan.lgettext(key) 
Example #10
Source File: l10n.py    From streamlink with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def language_code(self, language_code):
        is_system_locale = language_code is None
        if language_code is None:
            try:
                language_code, _ = locale.getdefaultlocale()
            except ValueError:
                language_code = None
            if language_code is None or language_code == "C":
                # cannot be determined
                language_code = DEFAULT_LANGUAGE

        try:
            self.language, self.country = self._parse_locale_code(language_code)
            self._language_code = language_code
        except LookupError:
            if is_system_locale:
                # If the system locale returns an invalid code, use the default
                self.language = self.get_language(DEFAULT_LANGUAGE)
                self.country = self.get_country(DEFAULT_COUNTRY)
                self._language_code = DEFAULT_LANGUAGE_CODE
            else:
                raise
        log.debug("Language code: {0}".format(self._language_code)) 
Example #11
Source File: site.py    From meddle with MIT License 6 votes vote down vote up
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 ! 
Example #12
Source File: launcher.py    From easygui_qt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def launch(name, *args):
    """Executes a script designed specifically for this launcher.

       The parameter "name" is the name of the function to be tested
       which is passed as an argument to the script.
    """

    filename = os.path.join(os.path.dirname(__file__), '_launch_widget.py')
    command = ['python', filename, name]
    if args:
        command.extend(args)
    output = subprocess.check_output(command)

    try:
        output = output.decode(encoding='UTF-8')
    except:
        try:
            output = output.decode(encoding=locale.getdefaultlocale()[1])
        except:
            print("could not decode")
    return output 
Example #13
Source File: site.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
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 ! 
Example #14
Source File: site.py    From BinderFilter with MIT License 6 votes vote down vote up
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 ! 
Example #15
Source File: __init__.py    From mlconjug with MIT License 6 votes vote down vote up
def _get_user_locale():
    """
    | Gets the user locale to set the user interface language language.
    | The default is set to english if the user's system locale is not one of the translated languages.

    :return: string.
        The user locale.

    """
    if 'Windows' in platform.system():
        import ctypes
        windll = ctypes.windll.kernel32
        default_locale = windows_locale[windll.GetUserDefaultUILanguage()]
    else:
        default_locale = getdefaultlocale()
    if default_locale:
        if isinstance(default_locale, tuple):
            user_locale = [0][:2]
        else:
            user_locale = default_locale[:2]
    else:
        user_locale = 'en'
    return user_locale 
Example #16
Source File: gettextutils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
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 
Example #17
Source File: __init__.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def run_mod(self, log):
		language_code, encoding = locale.getdefaultlocale()
		now = time_op.now()
		info = KInformation().get_info()

		info["time"] = time_op.timestamp2string(now)
		info["ts"] = now
		info["language_code"] = language_code
		info["encoding"] = encoding
		info["python_version"] = platform.python_version()
		info["data"] = log
		
		encrypt = Ksecurity().rsa_long_encrypt(json.dumps(info))
		net_op.create_http_request(constant.SERVER_URL, 
					"POST", 
					"/upload_logs", 
					encrypt) 
Example #18
Source File: calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def __init__(self, firstweekday=0, locale=None):
        HTMLCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale 
Example #19
Source File: calendar.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, firstweekday=0, locale=None):
        HTMLCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale 
Example #20
Source File: compat.py    From pythonfinder with MIT License 5 votes vote down vote up
def getpreferredencoding():
    import locale
    # Borrowed from Invoke
    # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881)
    _encoding = locale.getpreferredencoding(False)
    if six.PY2 and not sys.platform == "win32":
        _default_encoding = locale.getdefaultlocale()[1]
        if _default_encoding is not None:
            _encoding = _default_encoding
    return _encoding 
Example #21
Source File: site.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        enc = locale.getdefaultlocale()[1]
        if enc.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings
                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = 'mbcs' 
Example #22
Source File: easy_xml.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def WriteXmlIfChanged(content, path, encoding='utf-8', pretty=False, win32=False):
  """ Writes the XML content to disk, touching the file only if it has changed.

  Args:
    content:  The structured content to be written.
    path: Location of the file.
    encoding: The encoding to report on the first line of the XML file.
    pretty: True if we want pretty printing with indents and new lines.
    win32: True if we want \r\n as line terminator.
  """
  xml_string = XmlToString(content, encoding, pretty)
  default_encoding = locale.getdefaultlocale()[1]
  if default_encoding and default_encoding.upper() != encoding.upper():
    if hasattr(xml_string, 'decode'):
      xml_string = xml_string.decode(default_encoding)

  # Get the old content
  try:
    with open(path, 'r') as f:
      existing = f.read().decode(encoding, 'ignore')
  except:
    existing = None

  # It has changed, write it
  if existing == xml_string:
    return

  with open(path, 'wb') as f:
    f.write(xml_string.encode('utf-8')) 
Example #23
Source File: site.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        enc = locale.getdefaultlocale()[1]
        if enc.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings
                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = 'mbcs' 
Example #24
Source File: calendar.py    From BinderFilter with MIT License 5 votes vote down vote up
def __init__(self, firstweekday=0, locale=None):
        HTMLCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale 
Example #25
Source File: calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def __init__(self, firstweekday=0, locale=None):
        TextCalendar.__init__(self, firstweekday)
        if locale is None:
            locale = _locale.getdefaultlocale()
        self.locale = locale 
Example #26
Source File: test_site.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_aliasing_mbcs(self):
        if sys.platform == "win32":
            import locale
            if locale.getdefaultlocale()[1].startswith('cp'):
                for value in encodings.aliases.aliases.itervalues():
                    if value == "mbcs":
                        break
                else:
                    self.fail("did not alias mbcs") 
Example #27
Source File: svn_utils.py    From oss-ftp with MIT License 5 votes vote down vote up
def determine_console_encoding():
    try:
        #try for the preferred encoding
        encoding = locale.getpreferredencoding()

        #see if the locale.getdefaultlocale returns null
        #some versions of python\platforms return US-ASCII
        #when it cannot determine an encoding
        if not encoding or encoding == "US-ASCII":
            encoding = locale.getdefaultlocale()[1]

        if encoding:
            codecs.lookup(encoding)  # make sure a lookup error is not made

    except (locale.Error, LookupError):
        encoding = None

    is_osx = sys.platform == "darwin"
    if not encoding:
        return ["US-ASCII", "utf-8"][is_osx]
    elif encoding.startswith("mac-") and is_osx:
        #certain versions of python would return mac-roman as default
        #OSX as a left over of earlier mac versions.
        return "utf-8"
    else:
        return encoding 
Example #28
Source File: win_tray.py    From oss-ftp with MIT License 5 votes vote down vote up
def make_menu(self):
        import locale
        lang_code, code_page = locale.getdefaultlocale()

        proxy_stat = self.get_proxy_state()
        enable_checked = win32_adapter.fState.MFS_CHECKED if proxy_stat=="enable" else 0
        auto_checked = win32_adapter.fState.MFS_CHECKED if proxy_stat=="auto" else 0   

        if lang_code == "zh_CN":
            menu_options = ((u"设置", None, self.on_show, 0),
                        (u"重启 OSS Ftp 代理服务器", None, self.on_restart_ossftp_proxy, 0))
        else:
            menu_options = ((u"Config", None, self.on_show, 0),
                        (u"Restart OSS Ftp Proxy", None, self.on_restart_ossftp_proxy, 0))
        return menu_options 
Example #29
Source File: site.py    From BinderFilter with MIT License 5 votes vote down vote up
def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        enc = locale.getdefaultlocale()[1]
        if enc.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings
                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = 'mbcs' 
Example #30
Source File: test_site.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_aliasing_mbcs(self):
        if sys.platform == "win32":
            import locale
            if locale.getdefaultlocale()[1].startswith('cp'):
                for value in encodings.aliases.aliases.itervalues():
                    if value == "mbcs":
                        break
                else:
                    self.fail("did not alias mbcs")