LoginSignup
18

More than 5 years have passed since last update.

[Visual Studio Code][Python][Windows] VSCodeのタスク/デバッグ出力でのPythonの日本語文字化け対応

Last updated at Posted at 2017-02-26

デバッグ時の日本語出力が文字化けして困ったので対応方法をメモ
どうも出力時に使われる端末がUTF-8ではないらしいです。

環境

  • Windows 10
  • Visual Studio Code 1.9.1
  • Python 3.5.1 32bit

VSCode 拡張機能:

1.タスクの出力の日本語が文字化けする

TODO: 未解決(Issueには挙がってるようです)

Tasks should support specifying the output encoding · Issue #3550 · Microsoft/vscode

タスクの出力も端末に流すようにすれば解決するようなコメントも見かけました。(未検証)

Run build task fails · Issue #20152 · Microsoft/vscode

[追記] Pythonの標準出力の設定を変更する

以下の設定を加えることでも対応が可能でした

標準出力のエンコーディングの変更
import sys
import io

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

Python3でUnicodeDecodeErrorに遭遇したときのTODOリスト - Qiita

2. デバッグ出力の日本語が文字化けする

launch.jsonに以下のような設定があることが前提です。(初期状態でデバッグの歯車マークを押すと生成されます)

launch.json
        {
            "name": "Integrated Terminal/Console",
            "type": "python",
            "request": "launch",
            "stopOnEntry": true,
            "pythonPath": "${config.python.pythonPath}",
            "program": "${file}",
            "cwd": "null",
            "console": "integratedTerminal",
            "debugOptions": [
                "WaitOnAbnormalExit",
                "WaitOnNormalExit"
            ]
        },

1.png

デバッグで、Integrated Terminal/Console を選択します。
一度実行して、表示された端末で以下を実行します。

端末をUTF-8に修正
端末> chcp 65001

これで以後の日本語出力は問題ないはずです。(端末は使いまわされますが、もし閉じてしまったら再度実行してください)

参考

Visual Studio Code - Visual Studio CodeのOUTPUTが文字化けする(42828)|teratail

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
18