Python源码示例:locale.getdefaultlocale()
示例1
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
示例2
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)
示例3
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
示例4
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 !
示例5
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)
示例6
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 !
示例7
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
示例8
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 !
示例9
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 !
示例10
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 !
示例11
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))
示例12
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 !
示例13
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"
示例14
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 !
示例15
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 !
示例16
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
示例17
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)
示例18
def __init__(self, firstweekday=0, locale=None):
TextCalendar.__init__(self, firstweekday)
if locale is None:
locale = _locale.getdefaultlocale()
self.locale = locale
示例19
def __init__(self, firstweekday=0, locale=None):
HTMLCalendar.__init__(self, firstweekday)
if locale is None:
locale = _locale.getdefaultlocale()
self.locale = locale
示例20
def _language():
try:
language = locale.getdefaultlocale()
except ValueError:
language = DEFAULT_LOCALE_LANGUAGE
return language
示例21
def get_string(self):
output = launch('get_string')
if sys.version_info < (3,):
output = output.encode(encoding=locale.getdefaultlocale()[1])
self.label['get_string'].setText("{}".format(output))
示例22
def get_password(self):
output = launch('get_password')
if sys.version_info < (3,):
output = output.encode(encoding=locale.getdefaultlocale()[1])
self.label['get_password'].setText("{}".format(output))
示例23
def get_username_password(self):
output = launch('get_username_password')
if sys.version_info < (3,):
output = output.encode(encoding=locale.getdefaultlocale()[1])
self.label['get_username_password'].setText("{}".format(output))
示例24
def get_many_strings(self):
output = launch('get_many_strings')
if sys.version_info < (3,):
output = output.encode(encoding=locale.getdefaultlocale()[1])
self.label['get_many_strings'].setText("{}".format(output))
示例25
def get_date(self):
output = launch('get_date')
if sys.version_info < (3,):
output = output.encode(encoding=locale.getdefaultlocale()[1])
self.label['get_date'].setText("{}".format(output))
示例26
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)
示例27
def select_language(lang_code=""):
if not lang_code:
default_locale = locale.getdefaultlocale()[0]
lang = default_locale.split("_")
lang_code = lang[0] if len(lang) else "en"
if lang_code in Translation.available_languages():
Translation.lang_code = lang_code
else:
Translation.lang_code = "en"
Translation._load_lang(Translation.lang_code)
示例28
def safeExpandUser(filepath):
"""
@function Patch for a Python Issue18171 (http://bugs.python.org/issue18171)
"""
retVal = filepath
try:
retVal = os.path.expanduser(filepath)
except UnicodeDecodeError:
_ = locale.getdefaultlocale()
retVal = getUnicode(os.path.expanduser(filepath.encode(_[1] if _ and len(_) > 1 else UNICODE_ENCODING)))
return retVal
示例29
def insert_new_collection_entry(self, coll_uuid, title):
locale_lang = locale.getdefaultlocale()[0]
timestamp = int(time.time())
json_dict = {
"insert":
{
"type": "Collection",
"uuid": str(coll_uuid),
"lastAccess": timestamp,
"titles":
[
{
"display": title,
"direction": "LTR",
"language": locale_lang
}
],
"isVisibleInHome": 1,
"isArchived": 0,
"mimeType": "application/x-kindle-collection",
"collections": None
}
}
if self.is_cc_aware:
json_dict["insert"].update(
{
"collectionCount": None,
"collectionDataSetName": str(coll_uuid),
"isArchived": 1
})
self.commands.append(json_dict)
示例30
def to_calibre_plugin_json(self):
if self.original_ebooks == []:
return {}
else:
return {
"%s@%s" % (self.label, locale.getdefaultlocale()[0]):
{
"items": self.build_legacy_hashes_list(),
"lastAccess": int(time.time())
}
}
# it would be very, very unlucky to have a collision
# between collection uuid & label...