Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 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 | |
| 4 | Don't import directly from third-party code; use the `locale` module instead! |
| 5 | """ |
| 6 | |
| 7 | import sys |
| 8 | import _locale |
| 9 | |
| 10 | if sys.platform.startswith("win"): |
| 11 | def getpreferredencoding(do_setlocale=True): |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame] | 12 | if sys.flags.utf8_mode: |
| 13 | return 'UTF-8' |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 14 | return _locale._getdefaultlocale()[1] |
| 15 | else: |
| 16 | try: |
| 17 | _locale.CODESET |
Antoine Pitrou | 4aa8f8e | 2013-10-12 15:00:44 +0200 | [diff] [blame] | 18 | except AttributeError: |
Xavier de Gaye | 6c9dcda | 2016-12-17 09:19:11 +0100 | [diff] [blame] | 19 | if hasattr(sys, 'getandroidapilevel'): |
| 20 | # On Android langinfo.h and CODESET are missing, and UTF-8 is |
| 21 | # always used in mbstowcs() and wcstombs(). |
| 22 | def getpreferredencoding(do_setlocale=True): |
| 23 | return 'UTF-8' |
| 24 | else: |
| 25 | def getpreferredencoding(do_setlocale=True): |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame] | 26 | if sys.flags.utf8_mode: |
| 27 | return 'UTF-8' |
Xavier de Gaye | 6c9dcda | 2016-12-17 09:19:11 +0100 | [diff] [blame] | 28 | # This path for legacy systems needs the more complex |
| 29 | # getdefaultlocale() function, import the full locale module. |
| 30 | import locale |
| 31 | return locale.getpreferredencoding(do_setlocale) |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 32 | else: |
| 33 | def getpreferredencoding(do_setlocale=True): |
| 34 | assert not do_setlocale |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame] | 35 | if sys.flags.utf8_mode: |
| 36 | return 'UTF-8' |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 37 | result = _locale.nl_langinfo(_locale.CODESET) |
| 38 | if not result and sys.platform == 'darwin': |
| 39 | # nl_langinfo can return an empty string |
| 40 | # when the setting has an invalid value. |
| 41 | # Default to UTF-8 in that case because |
| 42 | # UTF-8 is the default charset on OSX and |
| 43 | # returning nothing will crash the |
| 44 | # interpreter. |
| 45 | result = 'UTF-8' |
| 46 | return result |