Set sys.stdout.encoding properly.
Always set LC_CTYPE on interpreter startup.
Add device_encoding function.
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
index bb69b19..cc0926a 100644
--- a/Python/pythonrun.c
+++ b/Python/pythonrun.c
@@ -154,7 +154,6 @@
 	char *p;
 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
 	char *codeset;
-	char *saved_locale;
 #endif
 	extern void _Py_ReadyTypes(void);
 
@@ -162,6 +161,13 @@
 		return;
 	initialized = 1;
 
+#ifdef HAVE_SETLOCALE
+	/* Set up the LC_CTYPE locale, so we can obtain
+	   the locale's charset without having to switch
+	   locales. */
+	setlocale(LC_CTYPE, "");
+#endif
+
 	if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
 		Py_DebugFlag = add_flag(Py_DebugFlag, p);
 	if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
@@ -254,8 +260,6 @@
 	   initialized by other means. Also set the encoding of
 	   stdin and stdout if these are terminals.  */
 
-	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
-	setlocale(LC_CTYPE, "");
 	codeset = nl_langinfo(CODESET);
 	if (codeset && *codeset) {
 		PyObject *enc = PyCodec_Encoder(codeset);
@@ -268,8 +272,6 @@
 		}
 	} else
 		codeset = NULL;
-	setlocale(LC_CTYPE, saved_locale);
-	free(saved_locale);
 
 	if (codeset) {
 		if (!Py_FileSystemDefaultEncoding)