Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 85c386d

Browse files
Issue #25182: The stdprinter (used as sys.stderr before the io module is
imported at startup) now uses the backslashreplace error handler.
2 parents 9a14214 + 008fc77 commit 85c386d

2 files changed

Lines changed: 24 additions & 4 deletions

File tree

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ Release date: TBA
180180
Core and Builtins
181181
-----------------
182182

183+
- Issue #25182: The stdprinter (used as sys.stderr before the io module is
184+
imported at startup) now uses the backslashreplace error handler.
185+
183186
- Issue #25131: Make the line number and column offset of set/dict literals and
184187
comprehensions correspond to the opening brace.
185188

Objects/fileobject.c

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -372,8 +372,11 @@ PyFile_NewStdPrinter(int fd)
372372
static PyObject *
373373
stdprinter_write(PyStdPrinter_Object *self, PyObject *args)
374374
{
375+
PyObject *unicode;
376+
PyObject *bytes = NULL;
375377
char *str;
376378
Py_ssize_t n;
379+
int _errno;
377380

378381
if (self->fd < 0) {
379382
/* fd might be invalid on Windows
@@ -383,13 +386,27 @@ stdprinter_write(PyStdPrinter_Object *self, PyObject *args)
383386
Py_RETURN_NONE;
384387
}
385388

386-
/* encode Unicode to UTF-8 */
387-
if (!PyArg_ParseTuple(args, "s", &str))
389+
if (!PyArg_ParseTuple(args, "U", &unicode))
388390
return NULL;
389391

390-
n = _Py_write(self->fd, str, strlen(str));
392+
/* encode Unicode to UTF-8 */
393+
str = PyUnicode_AsUTF8AndSize(unicode, &n);
394+
if (str == NULL) {
395+
PyErr_Clear();
396+
bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace");
397+
if (bytes == NULL)
398+
return NULL;
399+
if (PyBytes_AsStringAndSize(bytes, &str, &n) < 0) {
400+
Py_DECREF(bytes);
401+
return NULL;
402+
}
403+
}
404+
405+
n = _Py_write(self->fd, str, n);
406+
_errno = errno;
407+
Py_XDECREF(bytes);
391408
if (n == -1) {
392-
if (errno == EAGAIN) {
409+
if (_errno == EAGAIN) {
393410
PyErr_Clear();
394411
Py_RETURN_NONE;
395412
}

0 commit comments

Comments
 (0)