PyScripter でパスに日本語を含むとUnicodeEncodeErrorとなる対応

Python IDE の PyScripter 。Linuxに対応していないのが残念だが、軽量でかなり使いやすい。

ソースコードまでのパスに、日本語(非ASCII文字)が含まれると、PyScripterからの実行、デバッグ実行時に、

UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 8-10: ordinal not in range(128)

てなエラーが発生する。

 

パスに、"テスト"という日本語が含まれるため、エラーとなっている。

pyscripter_encode_err01

python コマンドで実行するなり、ダブルクリックで実行するなり、PyScripter以外からこのファイルを実行する分には問題ない。

まぁ、日本語をパスに含まないようにすればよいのだが、面倒だ。

https://code.google.com/p/pyscripter/issues/detail?id=427

 

Python のインストールフォルダ直下の Lib フォルダに、site.py ファイルがあるので、これを編集する。

例えば、

C:\Python27\Lib\site.py

をテキストエディタで開き、def setencoding() の最初の if 0:if 1: に変更する

  1. def setencoding():
  2. """Set the string encoding used by the Unicode implementation. The
  3. default is 'ascii', but if you're willing to experiment, you can
  4. change this."""
  5. encoding = "ascii" # Default value set by _PyUnicode_Init()
  6. ### ↓↓↓ ここを、0 -> 1 に変更
  7. if 1:
  8. # Enable to support locale aware default string encodings.
  9. import locale
  10. loc = locale.getdefaultlocale()
  11. if loc[1]:
  12. encoding = loc[1]
  13. if 0:
  14. # Enable to switch off string to Unicode coercion and implicit
  15. # Unicode to string conversion.
  16. encoding = "undefined"
  17. if encoding != "ascii":
  18. # On Non-Unicode builds this will raise an AttributeError...
  19. sys.setdefaultencoding(encoding) # Needs Python Unicode build !

実行してみる。

エラーとならずに、実行できた!

pyscripter_encode_err02

。。。はよいが、Python自体の設定を変更しているので、副作用が気になる。

コードを見ると、locale.getdefaultlocale() の 2つめの要素を、sys.setdefaultencoding に与えている。

自分の環境だと、cp932。

  1. >>> import locale
  2. >>> locale.getdefaultlocale()
  3. ('ja_JP', 'cp932')

上記、site.py を編集する前に、sys.getdefaultencoding() を実行すると、ascii が返るが、、、

  1. >>> import site
  2. >>> sys.getdefaultencoding()
  3. 'ascii'

編集後は、cp932 が返るようになる。

  1. >>> import sys
  2. >>> sys.getdefaultencoding()
  3. 'cp932'

http://python.rdy.jp/wiki.cgi?page=japaneseCharset

sys.setdefaultencodingは文字コードのこと考えていない古いソースコードのためにある設定項目なので、これから何か新しいものを書こうとするプログラマが設定する必要はありません。

Pythonは書けないが、海外で作られたアプリやMODユーティリティが UnicodeEncodeError/UnicodeDecodeError で動かないという方は、次のような設定で回避できる場合があります。

方法1:sitecustomize.pyを書き換える

Windows であれば C:\Python27\Lib\site-package\sitecustomize.py

Unix であれば /usr/lib/python2.7/site-package/sitecustomize.py

というファイル[3]に以下の2行を追記してください。ただし、「********」は、お使いのファイルシステムの文字コード(Windowsならcp932、Unixならたぶんutf-8)に置き換えてください。

import sys

sys.setdefaultencoding(‘********’)

以上の設定はPython全体で有効です。

とのことなので、設定しても良さそうな感じ。

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です