Stringio Portability Between Python2 And Python3 When Capturing Stdout
I have written a python package which I have managed to make fully compatible with both python 2.7 and python 3.4, with one exception that is stumping me so far. The package includ
Solution 1:
You replaced the Python 2 bytes-only sys.stdout
with one that only takes Unicode. You'll have to adjust your strategy on the Python version here, and use a different object:
try:
# Python 2from cStringIO import StringIO
except ImportError:
# Python 3from io import StringIO
and remove the io.
prefix in your context manager:
origout, sys.stdout = sys.stdout, StringIO()
The cStringIO.StringIO
object is the Python 2 equivalent of io.BytesIO
; it requires that you write plain bytestrings, not aunicode
objects.
You can also use io.BytesIO
in Python 2, but then you want to test if sys.stdout
is a io.TextIOBase
subclass; if it is not, replace the object with a binary BytesIO
, object, otherwise use a StringIO
object:
import ioif isinstance(sys.stdout, io.TextIOBase):
# Python 3
origout, sys.stdout = sys.stdout, io.StringIO()
else:
# Python 2or an unorthodox binary stdout setup
origout, sys.stdout = sys.stdout, io.BytesIO()
Solution 2:
Have your tried? (Can be left in your code under Python 3.x)
from __future__ import unicode_literals
Else what I have in my code to make it compatible when using io.StringIO
:
f = io.StringIO(datafile.read().decode('utf-8'), newline=None)
Looking at your code then:
yield (rtn, sys.stdout.read())
Could be changed to:
yield (rtn, sys.stdout.read().decode('utf-8'))
Post a Comment for "Stringio Portability Between Python2 And Python3 When Capturing Stdout"