python – Wrap an open stream with io.TextIOWrapper

python – Wrap an open stream with io.TextIOWrapper

Use codecs.getreader to produce a wrapper object:

text_stream = codecs.getreader(utf-8)(bytes_stream)

Works on Python 2 and Python 3.

It turns out you just need to wrap your io.BytesIO in io.BufferedReader which exists on both Python 2 and Python 3.

import io

reader = io.BufferedReader(io.BytesIO(Lorem ipsum.encode(utf-8)))
wrapper = io.TextIOWrapper(reader)
wrapper.read()  # returns Lorem ipsum

This answer originally suggested using os.pipe, but the read-side of the pipe would have to be wrapped in io.BufferedReader on Python 2 anyway to work, so this solution is simpler and avoids allocating a pipe.

python – Wrap an open stream with io.TextIOWrapper

Based on multiple suggestions in various forums, and experimenting with the standard library to meet the criteria, my current conclusion is this cant be done with the library and types as we currently have them.

Leave a Reply

Your email address will not be published.