2013年1月10日木曜日

[Python]標準出力の文字コードを指定

Example: test02.py
# -*- coding: utf-8 -*-
import sys
import codecs

# コマンドプロンプトの文字コードを cp65001 (UTF-8) にしておくと
# LookupError: unknown encoding: cp65001
# と表示されるので cp65001 が utf-8 であると登録しておく

def cp65001(name):
    if name.lower() == 'cp65001':
        return codecs.lookup('utf-8')

codecs.register(cp65001)
print sys.stdout.encoding

# そのままでは文字化けで表示される
# stdout の文字コードを UTF-8 に変更する
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

print "あ"
print u"あ"
実行結果
> python test02.py
cp65001
Traceback (most recent call last):
  File "test02.py", line 20, in 
    print "(文字化け)"
  File "C:\usr\Python27\lib\codecs.py", line 351, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)
str 型は表示できないとエラーが出る

0 件のコメント:

コメントを投稿