Atom
UnicodeDecodeError 'cp950' codec can't decode

UnicodeDecodeError 'cp950' codec can't decode

UnicodeDecodeError(cp950 無法解碼)

subprocess輸出包含中文特殊符號,但Python在背景thread用cp950去讀導致程式崩潰
要使用cp65001才行(就是UTF-8)

解決方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import subprocess
import threading

def run_subprocess(cmd):
"""
安全呼叫 subprocess,永遠用 UTF-8 解碼並避免因特殊字元炸掉。
"""
try:
result = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace"
)
return result.stdout
except Exception as e:
print(f"[ERROR] {e}")
return ""

def main():
cmd = ["your_command_here"]

output = run_subprocess(cmd)

# 防止 NoneType
if output and output.strip():
print("=== Output ===")
print(output)
else:
print("[INFO] No output (or only whitespace).")

if __name__ == "__main__":
main()

若是其他工具要使用也可以寫一個通用的fuction

1
2
3
4
5
6
7
8
9
def run_cmd(cmd):
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="ignore"
)
return result.stdout.strip()

這樣在使用任何工具都可以直接使用cp65001了
例如

  • nmap
    1
    2
    run_cmd(["nmap", "-Pn", "10.0.0.5"])

  • openssl
    1
    run_cmd(["openssl", "x509", "-in", "cert.pem", "-noout", "-text"])
本文作者:Atom
本文鏈接:https://d0ngd.github.io/2025/12/04/UnicodeDecodeError 'cp950' codec can't decode/
版權聲明:本文採用 CC BY-NC-SA 3.0 CN 協議進行許可