_bootlocale.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """A minimal subset of the locale module used at interpreter startup
  2. (imported by the _io module), in order to reduce startup time.
  3. Don't import directly from third-party code; use the `locale` module instead!
  4. """
  5. import sys
  6. import _locale
  7. if sys.platform.startswith("win"):
  8. def getpreferredencoding(do_setlocale=True):
  9. if sys.flags.utf8_mode:
  10. return 'UTF-8'
  11. return _locale._getdefaultlocale()[1]
  12. else:
  13. try:
  14. _locale.CODESET
  15. except AttributeError:
  16. if hasattr(sys, 'getandroidapilevel'):
  17. # On Android langinfo.h and CODESET are missing, and UTF-8 is
  18. # always used in mbstowcs() and wcstombs().
  19. def getpreferredencoding(do_setlocale=True):
  20. return 'UTF-8'
  21. else:
  22. def getpreferredencoding(do_setlocale=True):
  23. if sys.flags.utf8_mode:
  24. return 'UTF-8'
  25. # This path for legacy systems needs the more complex
  26. # getdefaultlocale() function, import the full locale module.
  27. import locale
  28. return locale.getpreferredencoding(do_setlocale)
  29. else:
  30. def getpreferredencoding(do_setlocale=True):
  31. assert not do_setlocale
  32. if sys.flags.utf8_mode:
  33. return 'UTF-8'
  34. result = _locale.nl_langinfo(_locale.CODESET)
  35. if not result and sys.platform == 'darwin':
  36. # nl_langinfo can return an empty string
  37. # when the setting has an invalid value.
  38. # Default to UTF-8 in that case because
  39. # UTF-8 is the default charset on OSX and
  40. # returning nothing will crash the
  41. # interpreter.
  42. result = 'UTF-8'
  43. return result