ぱたへね

はてなダイアリーはrustの色分けができないのでこっちに来た

PyCharm で日本語入りソースを読み込むとUnicodeDecodeError

PyCharm 1.5.4を、Windows環境の Python3.2 で動かしていたら、タイトルのエラーが出て、少しはまりました。解決策をまとめました。
PyCharmから日本語が入ったPythonソースを、Debugで実行するとこのようなエラーがでます。DebugではなくRunなら問題なく動作します。

C:\Python32\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 1.5.4\helpers\pydev\pydevd.py" --client 127.0.0.1 --port 8793 --file C:/home/Dropbox/python/PAIP/ch5/eliza.py
pydev debugger: starting
Connected to pydev debugger (build 107.576)
Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm 1.5.4\helpers\pydev\pydevd.py", line 1204, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\Program Files (x86)\JetBrains\PyCharm 1.5.4\helpers\pydev\pydevd.py", line 967, in run
    line = stream.readline() #Should not raise an exception even if there are no more contents
UnicodeDecodeError: 'cp932' codec can't decode bytes in position 182-183: illegal multibyte sequence

問題になっているのはpydevd.py967行目。ソースを見る限り、2行読み込んで'coding'の文字列を探しているのですが、そのソース自体がutf-8で読み込まれていないのでUnicodeDecodeErrorがでます。Python3じゃなければ大丈夫そうですね。

        if not IS_PY3K:
            execfile(file, globals, locals) #execute the script
        else:
            stream = open(file)
            try:
                encoding = None
                #Get encoding!
                for i in range(2):
                    line = stream.readline() #Should not raise an exception even if there are no more contents
                    #Must be a comment line
                    if line.strip().startswith('#'):
                        #Don't import re if there's no chance that there's an encoding in the line
                        if 'coding' in line:
                            import re
                            p = re.search(r"coding[:=]\s*([-\w.]+)", line)
                            if p:
                                encoding = p.group(1)
                                break
            finally:
                stream.close()

やっつけですが、utf-8しか使わないのであれば、最初のファイルを開くときもutf-8を指定すればこの問題は解決します。

# stream = open(file)
stream = open(file, encoding='utf-8')

ちなみにPyCharm Beta2.0ではこの問題は起きません。