Starting in Python 3, you can also use sys.stdout.buffer.write()
to write (already) encoded byte strings to standard output (see standard output in Python 3 ). When you do this, the simple StringIO
approach StringIO
not work, because neither sys.stdout.encoding
nor sys.stdout.buffer
will be available.
Starting with Python 2.6, you can use the TextIOBase
API , which includes missing attributes:
import sys from io import TextIOWrapper, BytesIO
This solution works for Python 2> = 2.6 and Python 3. Note that our sys.stdout.write()
only accepts Unicode strings, and sys.stdout.buffer.write()
only accepts byte strings. This may not apply to the old code, but often it refers to the code that was created to run on Python 2 and 3 without changes.
If you need to maintain code that sends byte strings to stdout directly, without using stdout.buffer, you can use this option:
class StdoutBuffer(TextIOWrapper): def write(self, string): try: return super(StdoutBuffer, self).write(string) except TypeError:
You do not need to set the encoding of the sys.stdout.encoding buffer, but it helps when using this method to test / compare the output of the script.
JonnyJD Oct 13 '13 at 11:52 2013-10-13 11:52
source share