その後のその後

iOSエンジニア 堤 修一のブログ github.com/shu223

Python スクリプト実行時に UnicodeDecodeError が出る場合の対処方法

Xcode の Run Script 機能を使ってみようと思い、Github で拾ってきた Python スクリプトを実行しようとすると、下記のようなエラーが出て困りました。

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position xx: ordinal not in range(128)

対処手順

1. 現状のデフォルトエンコーディングを確認

$ python
>>> import sys
>>> sys.getdefaultencoding()
'ascii'

これが'ascii'となっているのがよくないようです。


2. site-packagesディレクトリの場所を探す
まず、

python

と打ったときにわらわらと出てくる文字列で自分の環境でのpythonのバージョンが確認できます。


で、自分の場合は2.7.1が入っていたので、site-packagesというディレクトリは以下のパスにありました。

/Library/Python/2.7/site-packages/


3. sitecustomize.py を作成
2のディレクトリ配下に、sitecustomize.py という名前のファイルを作成します。

import sys
sys.setdefaultencoding('utf-8')


4. 変更されたか確認

$ python
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

上記のように、utf-8となっていれば成功!


参考ページ
http://d.hatena.ne.jp/yukihir0/20110131/1296478348
http://blog.livedoor.jp/kaz0215/archives/51124286.html
http://camge.tumblr.com/post/10694956820/how-to-change-default-encoding-to-utf-8-in-python