10/06/2010

Pydevのデバッガーがエラーになる件

EclipseでPythonを触ってみようとして、はまったのでメモしておく

python 3.1
pydev 1.6.2
実行環境は別途落としてきた3.1を利用。

debug実行時にソースにダブルバイトのコメントが存在した場合、

#あ
n=1
print("hoge")


エラーは以下

pydev debugger: starting
Traceback (most recent call last):
File "C:\util\ide\eclipse36\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\pydevd.py", line 1147, in
debugger.run(setup['file'], None, None)
File "C:\util\ide\eclipse36\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\pydevd.py", line 925, 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 55-56: illegal multibyte sequence

encodeはutf-8に設定してるのだが?pydevd.pyのエラー箇所をみてる。

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()


の line = stream.readline()でエラー。
その上で、cp932でstream = open(file)してしまってるためっぽい。
openしてcodingを調べたいのに、cp932で開いてエラーになる

ソース先頭2行目までに、# coding: utf-8
があれば、stream = open(file, encoding='utf-8')のとこだけの変更でよいが、
encoding='utf-8'もいれといた。


if not IS_PY3K:
execfile(file, globals, locals) #execute the script
else:
#stream = open(file) #2010.10.6 cahnge
stream = open(file, encoding='utf-8')
try:
#encoding = None #2010.10.6 cahnge
encoding='utf-8'
#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()

if encoding:
stream = open(file, encoding=encoding)
else:
stream = open(file)
try:
contents = stream.read()
finally:
stream.close()


他にもっと、ちゃんとしたやり方がある筈なのだが、初心者なのでよくわからん。
動くようになったから、とりあえずこれでいいや。


2011-01-16 追記
バグトラッカに報告された模様、有難いことです。
http://suzumizaki.blog6.fc2.com/blog-entry-157.html
私も世の中に、貢献できるような人間になりたい。。

4 件のコメント:

匿名 さんのコメント...

助かりました。

kobito さんのコメント...

こんなpostでも役にたてて良かった。

鈴見咲 君高 さんのコメント...

こんにちは。別件を検索してこのページにたどり着きましたが。重要そうなのに今も修正されていないようなのでPydevのバグトラッカに登録しておきました。実はopen(file, encoding="utf-8")では解決にならなかったりしますが、私のやり方でも完璧かというとちょっと怪しいです。

kobito さんのコメント...

鈴見咲 君高 様
バグ登録ご苦労様です!

何分、素人のソノ場しのぎなもので。。

なるほどー。
open(file, "rb")で判定してからですよねぇ。