Eryk Sun <eryk...@gmail.com> added the comment:

The sys.stdout TextIOWrapper is stuck in a bad state. When the write() method 
is called with an ASCII string, it implements an optimization that stores a 
reference to the str() object in the internal pending_bytes instead of 
immediately encoding the string. Subsequently _textiowrapper_writeflush() 
attempts to create a bytes object for this ASCII string, but 
PyBytes_FromStringAndSize fails with a memory error. It's stuck in this state 
because it will never be able to flush the string. 

The first workaround I thought of was to call to detach() to rewrap 
sys.stdout.buffer with a new TextIOWrapper instance, but detach() attempts to 
flush and fails. A hacky but simple and effective workaround is to just 
re-initialize the wrapper. For example:

    sys.stdout.__init__(sys.stdout.buffer, sys.stdout.encoding,
        sys.stdout.errors, None, True)

This clears the internal pending_bytes.

----------
components: +IO
nosy: +eryksun
priority: normal -> high
versions: +Python 3.10, Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue43260>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to