0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsのsubprocessで文字化けする原因:cp932決め打ちをやめて実バイトを見る

0
Posted at

はじめに

Pythonの subprocess でWindowsのコマンド出力を受け取るとき、encoding="cp932" を決め打ちして文字化けする——よくある対処ですが、出力が本当にcp932とは限りません。PowerShell 7やUTF-8設定の環境では、出力はUTF-8です。

この記事では、実際の出力バイトを確認し、決め打ちが壊れる例と安全な扱いを実測します。

環境

  • Windows 11(ビルド 10.0.26200)
  • Python 3.11.5
  • Windows PowerShell 5.1.26100

やったこと

1. 出力バイトを見る

import subprocess

p = subprocess.run(
    ["powershell", "-NoProfile", "-Command", "Write-Output '日本語テスト'"],
    capture_output=True,
)
print(p.stdout[:40])

結果:

b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88\r\n'

e6 97 a5 はUTF-8の「日」です。cp932ではありません。

2. cp932でデコードすると失敗する

try:
    print(p.stdout.decode("cp932"))
except UnicodeDecodeError as e:
    print(type(e).__name__, e)

結果:

UnicodeDecodeError 'cp932' codec can't decode byte 0x88 in position 17: illegal multibyte sequence

3. UTF-8でデコードすると通る

print(p.stdout.decode("utf-8").strip())

結果:

日本語テスト

4. text=True の既定はロケール依存

p2 = subprocess.run(
    ["powershell", "-NoProfile", "-Command", "Write-Output '日本語テスト'"],
    capture_output=True, text=True,
)
print(p2.stdout.strip())

この環境ではロケールがUTF-8のため、そのまま読めました。しかし、ロケールがcp932の環境では結果が変わります。実行環境のロケールに依存することを覚えておきます。

5. 出力側のエンコーディングを明示する

PowerShell側でUTF-8を明示すると、受け取る側も安定します。

p3 = subprocess.run(
    ["powershell", "-NoProfile", "-Command",
     "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); Write-Output '日本語テスト'"],
    capture_output=True, text=True, encoding="utf-8",
)
print(p3.stdout.strip())

結果:

日本語テスト

6. 壊れた文字を落とさずに読む

相手の出力形式が分からない場合は、errors="replace" で例外を避けつつ、置換文字が出たらログに残します。

text = p.stdout.decode("utf-8", errors="replace")
if "\ufffd" in text:
    print("デコードに失敗したバイトがあります")

ハマった点

encoding="cp932" は「Windowsだから」では正当化できない

Windowsでも、PowerShell 7、chcp 65001、[Console]::OutputEncoding の設定によって出力はUTF-8になります。まずバイト列を見て、実際のエンコーディングを確認します。

text=True だけでは不十分

text=True はロケールのエンコーディングを使います。実行環境が変わると挙動が変わるため、外部ツールとの連携では encoding を明示するか、バイトで受けてからデコードします。

エラーを握りつぶさない

errors="ignore" は文字が消えるため、デバッグが難しくなります。errors="replace" で置換文字を残し、必要なら元のバイト列もログに保存します。

まとめ

  • Windowsのコマンド出力がcp932とは限らない。まず stdout のバイト列を見る。
  • この環境のPowerShell出力はUTF-8(e6 97 a5 ...)だった。
  • text=True はロケール依存。外部ツールでは encoding を明示する。
  • 出力側で [Console]::OutputEncoding をUTF-8にすると安定する。
  • 不明な場合は errors="replace" で置換文字を検出する。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?