@@ -619,53 +619,49 @@ def resetlocale(category=LC_ALL):
619619 """
620620 _setlocale (category , _build_localename (getdefaultlocale ()))
621621
622- if sys .platform .startswith ("win" ):
623- # On Win32, this will return the ANSI code page
624- def getpreferredencoding (do_setlocale = True ):
625- """Return the charset that the user is likely using."""
622+
623+ try :
624+ from _locale import _get_locale_encoding
625+ except ImportError :
626+ def _get_locale_encoding ():
627+ if hasattr (sys , 'getandroidapilevel' ):
628+ # On Android langinfo.h and CODESET are missing, and UTF-8 is
629+ # always used in mbstowcs() and wcstombs().
630+ return 'UTF-8'
626631 if sys .flags .utf8_mode :
627632 return 'UTF-8'
628- import _bootlocale
629- return _bootlocale .getpreferredencoding (False )
633+ encoding = getdefaultlocale ()[1 ]
634+ if encoding is None :
635+ # LANG not set, default conservatively to ASCII
636+ encoding = 'ascii'
637+ return encoding
638+
639+ try :
640+ CODESET
641+ except NameError :
642+ def getpreferredencoding (do_setlocale = True ):
643+ """Return the charset that the user is likely using."""
644+ return _get_locale_encoding ()
630645else :
631646 # On Unix, if CODESET is available, use that.
632- try :
633- CODESET
634- except NameError :
635- if hasattr (sys , 'getandroidapilevel' ):
636- # On Android langinfo.h and CODESET are missing, and UTF-8 is
637- # always used in mbstowcs() and wcstombs().
638- def getpreferredencoding (do_setlocale = True ):
639- return 'UTF-8'
640- else :
641- # Fall back to parsing environment variables :-(
642- def getpreferredencoding (do_setlocale = True ):
643- """Return the charset that the user is likely using,
644- by looking at environment variables."""
645- if sys .flags .utf8_mode :
646- return 'UTF-8'
647- res = getdefaultlocale ()[1 ]
648- if res is None :
649- # LANG not set, default conservatively to ASCII
650- res = 'ascii'
651- return res
652- else :
653- def getpreferredencoding (do_setlocale = True ):
654- """Return the charset that the user is likely using,
655- according to the system configuration."""
656- if sys .flags .utf8_mode :
657- return 'UTF-8'
658- import _bootlocale
659- if do_setlocale :
660- oldloc = setlocale (LC_CTYPE )
661- try :
662- setlocale (LC_CTYPE , "" )
663- except Error :
664- pass
665- result = _bootlocale .getpreferredencoding (False )
666- if do_setlocale :
667- setlocale (LC_CTYPE , oldloc )
668- return result
647+ def getpreferredencoding (do_setlocale = True ):
648+ """Return the charset that the user is likely using,
649+ according to the system configuration."""
650+ if sys .flags .utf8_mode :
651+ return 'UTF-8'
652+
653+ if not do_setlocale :
654+ return _get_locale_encoding ()
655+
656+ old_loc = setlocale (LC_CTYPE )
657+ try :
658+ try :
659+ setlocale (LC_CTYPE , "" )
660+ except Error :
661+ pass
662+ return _get_locale_encoding ()
663+ finally :
664+ setlocale (LC_CTYPE , old_loc )
669665
670666
671667### Database
0 commit comments