Set sys.stdout.encoding properly.
Always set LC_CTYPE on interpreter startup.
Add device_encoding function.
diff --git a/Modules/_localemodule.c b/Modules/_localemodule.c
index 6f063fb..233cf02 100644
--- a/Modules/_localemodule.c
+++ b/Modules/_localemodule.c
@@ -1,5 +1,5 @@
 /***********************************************************
-Copyright (C) 1997, 2002, 2003 Martin von Loewis
+Copyright (C) 1997, 2002, 2003, 2007 Martin von Loewis
 
 Permission to use, copy, modify, and distribute this software and its
 documentation for any purpose and without fee is hereby granted,
@@ -562,7 +562,8 @@
             /* Check NULL as a workaround for GNU libc's returning NULL
                instead of an empty string for nl_langinfo(ERA).  */
             const char *result = nl_langinfo(item);
-            return PyString_FromString(result != NULL ? result : "");
+            /* XXX may have to convert this to wcs first. */
+            return PyUnicode_FromString(result != NULL ? result : "");
         }
     PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant");
     return NULL;
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
index 9d4d14f..61ac4e6 100644
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -92,6 +92,10 @@
 #include <sys/loadavg.h>
 #endif
 
+#ifdef HAVE_LANGINFO_H
+#include <langinfo.h>
+#endif
+
 /* Various compilers have only certain posix functions */
 /* XXX Gosh I wish these were all moved into pyconfig.h */
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -6581,6 +6585,43 @@
 }
 #endif
 
+PyDoc_STRVAR(device_encoding__doc__,
+"device_encoding(fd) -> str\n\n\
+Return a string describing the encoding of the device\n\
+if the output is a terminal; else return None.");
+
+static PyObject *
+device_encoding(PyObject *self, PyObject *args)
+{
+	int fd;
+	if (!PyArg_ParseTuple(args, "i:device_encoding", &fd))
+		return NULL;
+	if (!isatty(fd)) {
+		Py_INCREF(Py_None);
+		return Py_None;
+	}
+#if defined(MS_WINDOWS) || defined(MS_WIN64)
+	if (fd == 0) {
+		char buf[100];
+		sprintf(buf, "cp%d", GetConsoleCP());
+		return PyUnicode_FromString(buf);
+	}
+	if (fd == 1 || fd == 2) {
+		char buf[100];
+		sprintf(buf, "cp%d", GetConsoleOutputCP());
+		return PyUnicode_FromString(buf);
+	}
+#elif defined(CODESET)
+	{
+		char *codeset = nl_langinfo(CODESET);
+		if (codeset)
+			return PyUnicode_FromString(codeset);
+	}
+#endif
+	Py_INCREF(Py_None);
+	return Py_None;
+}
+
 #ifdef __VMS
 /* Use openssl random routine */
 #include <openssl/rand.h>
@@ -6793,6 +6834,7 @@
 #endif /* HAVE_TCSETPGRP */
 	{"open",	posix_open, METH_VARARGS, posix_open__doc__},
 	{"close",	posix_close, METH_VARARGS, posix_close__doc__},
+	{"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__},
 	{"dup",		posix_dup, METH_VARARGS, posix_dup__doc__},
 	{"dup2",	posix_dup2, METH_VARARGS, posix_dup2__doc__},
 	{"lseek",	posix_lseek, METH_VARARGS, posix_lseek__doc__},