Index: Modules/posixmodule.c =================================================================== --- Modules/posixmodule.c (revision 66633) +++ Modules/posixmodule.c (working copy) @@ -2326,14 +2326,16 @@ PyObject *d, *v; DIR *dirp; struct dirent *ep; - int arg_is_unicode = 1; + int arg_is_unicode = 1, force_unicode = 1; errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + if (!PyArg_ParseTuple(args, "U|i:listdir", &v, &force_unicode)) { arg_is_unicode = 0; + force_unicode = 0; PyErr_Clear(); } - if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) + if (!PyArg_ParseTuple(args, "et|i:listdir", Py_FileSystemDefaultEncoding, &name, + &force_unicode)) return NULL; if ((dirp = opendir(name)) == NULL) { return posix_error_with_allocated_filename(name); @@ -2367,7 +2369,7 @@ d = NULL; break; } - if (arg_is_unicode) { + if (arg_is_unicode || force_unicode) { PyObject *w; w = PyUnicode_FromEncodedObject(v, @@ -2377,11 +2379,16 @@ Py_DECREF(v); v = w; } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ + else if (!force_unicode && + PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { PyErr_Clear(); } + else { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } } if (PyList_Append(d, v) != 0) { Py_DECREF(v);