課題
sys.stdout のエンコードを変更したい!!!
説明
sys.stdout のエンコードの変更は,Python2.6 までは
>>> sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
>>> print u'ほげ'
ほげ
ってやります.
これを,Python3.0 でやると,
>>> sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
>>> print('ほげ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python30\lib\codecs.py", line 356, in write
self.stream.write(data)
File "C:\Python30\lib\io.py", line 1484, in write
s.__class__.__name__)
TypeError: can't write bytes to text stream
となり,text stream に bytes 型のデータは書き込めませんって起こられます.
これは,codecs.StreamWriter が byte stream を要求するにもかかわらず,text stream (sys.stdout は io.TextIOWrapper) を渡しているからです.
解決!!
さて,解決方法です.
>>> sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') >>> print('ほげ') ほげ
sys.stdout の元になる byte stream (sys.stdout.buffer) で io.TextIOWrapper を作り直してやるだけです.
io.TextIOWrapper の代わりに codecs.getwriter('utf-8') でもできますが,元が io.TextIOWrapper なのでお勧めしません.