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

Skip to content

Commit a59018c

Browse files
Issue #25182: The stdprinter (used as sys.stderr before the io module is
imported at startup) now uses the backslashreplace error handler.
1 parent b5102e3 commit a59018c

2 files changed

Lines changed: 25 additions & 6 deletions

File tree

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ Release date: tba
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #25182: The stdprinter (used as sys.stderr before the io module is
14+
imported at startup) now uses the backslashreplace error handler.
15+
1316
- Issue #24891: Fix a race condition at Python startup if the file descriptor
1417
of stdin (0), stdout (1) or stderr (2) is closed while Python is creating
1518
sys.stdin, sys.stdout and sys.stderr objects. These attributes are now set

Objects/fileobject.c

Lines changed: 22 additions & 6 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-
char *c;
375+
PyObject *unicode;
376+
PyObject *bytes = NULL;
377+
char *str;
376378
Py_ssize_t n;
379+
int _errno;
377380

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

386-
if (!PyArg_ParseTuple(args, "s", &c)) {
389+
if (!PyArg_ParseTuple(args, "U", &unicode))
387390
return NULL;
391+
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+
}
388403
}
389-
n = strlen(c);
390404

391405
Py_BEGIN_ALLOW_THREADS
392406
errno = 0;
393407
#ifdef MS_WINDOWS
394408
if (n > INT_MAX)
395409
n = INT_MAX;
396-
n = write(self->fd, c, (int)n);
410+
n = write(self->fd, str, (int)n);
397411
#else
398-
n = write(self->fd, c, n);
412+
n = write(self->fd, str, n);
399413
#endif
414+
_errno = errno;
400415
Py_END_ALLOW_THREADS
416+
Py_XDECREF(bytes);
401417

402418
if (n < 0) {
403-
if (errno == EAGAIN)
419+
if (_errno == EAGAIN)
404420
Py_RETURN_NONE;
405421
PyErr_SetFromErrno(PyExc_IOError);
406422
return NULL;

0 commit comments

Comments
 (0)