3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Windows環境下のPythonのprintで豆腐文字が出る問題への対策

Posted at

はじめに

Windowsでbash + python の環境を作っていた時に、標準出力のprintで、日本語が豆腐に文字化けする現象が発生したので、その対応策に関するメモです。

この記事に書いてあること

  • Windows上のPythonで標準入出力が文字化けする OR エラーを吐く 時の対処方法
  • Windows上のPythonでファイル読み書きが文字化けする OR エラーを吐く 時の対処方法

環境

  • OS: Windows10
  • 環境
    • 裏: git-for-windowsのbash および Msys2のzsh
    • 表: Cmder
  • python: anaconda python 3.7

何が問題か?

Python上で標準出力をしたとき、日本語が□(いわゆる豆腐)として表示されます。
よくある文字エンコーディング問題の一種で、matplotlibとかでよく見るやつです。

普段MacとLinuxしか使わないため、標準出力でこんな現象が発生すること自体知りませんでした。

対策

一昔前にデフォルトエンコーディングを設定したようなノリで、sitecustomize.pyを以下のように書き加えておきます。

import io, sys

# sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

これは標準出力と標準エラー出力をutf-8で吐き出せという命令です。これでutf-8で標準出力されるようになります。

※ sys.stdinは標準入力用。標準入力でも同じような問題が起きるため、ついでに追加しておくことをお勧めします。

余談:openのwirteでも似た問題が

fo = open('out.txt', 'w')
fo.write('正しく書き出せない')

ファイルオブジェクトにwriteしたときにも同様の問題が発生します。

標準出力の問題と同じようにsitecustomize.pyをいじるとなんとかなるかもしれないが、最近はファイルオブジェクトを開くときに文字エンコードを指定してやるのがスタンダードらしいので、私もそれに従うことにしました。

fo = open('out.txt', 'w', encoding='utf-8')
fo.write('正しく書き出せる')
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?