Index: Python/pythonrun.c =================================================================== --- Python/pythonrun.c (revision 61471) +++ Python/pythonrun.c (working copy) @@ -1159,10 +1159,53 @@ PyErr_PrintEx(1); } +static PyObject* +get_file_attr(PyObject *f, const char *name) +{ + PyObject *attr = PyObject_GetAttrString(f, name); + if (attr && PyUnicode_Check(attr)) + return attr; + Py_XDECREF(attr); + return NULL; +} + +static Py_ssize_t +get_length_in_bytes(PyObject *f, const char *text, Py_ssize_t size) +{ + PyObject *encoding = NULL, *errors = NULL, *unicode = NULL, *encoded = NULL; + Py_ssize_t len = strlen(text); + + encoding = get_file_attr(f, "encoding"); + if (encoding == NULL) + goto final; + + errors = get_file_attr(f, "errors"); + if (errors == NULL) + goto final; + + unicode = PyUnicode_FromStringAndSize(text, size); + if (unicode == NULL) + goto final; + + encoded = PyUnicode_AsEncodedString(unicode, PyUnicode_AsString(encoding), PyUnicode_AsString(errors)); + if (encoded == NULL) + goto final; + + len = PyString_GET_SIZE(encoded); + +final: + Py_XDECREF(encoding); + Py_XDECREF(errors); + Py_XDECREF(unicode); + Py_XDECREF(encoded); + return len; +} + static void print_error_text(PyObject *f, int offset, const char *text) { char *nl; + if (offset >= 0) { if (offset > 0 && offset == (int)strlen(text)) offset--; @@ -1184,6 +1227,7 @@ PyFile_WriteString("\n", f); if (offset == -1) return; + offset = get_length_in_bytes(f, text, offset); PyFile_WriteString(" ", f); offset--; while (offset > 0) {