QClaw运行Python脚本得到的结果总是乱码
现象
终端直接跑 python mcp_client.py read_table 7,中文正常。
同一个脚本通过 QClaw exec 工具调用,输出变成:
鎵撹祻銆 鍟婂疄鎵撳疄 鍙戞拻
排查
QClaw exec 管道用系统默认编码(Windows 中文环境 = cp936)捕获 stdout。
mcp_client.py 第 14 行:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
这行把 stdout 强行重写为 UTF-8 输出。
问题链条:
Python 脚本输出 UTF-8 字节
→ QClaw exec 管道捕获字节
→ 管道用 cp936 解码
→ ❌ 碰撞 → 乱码
终端直接跑不受影响,因为 Windows Terminal / PowerShell 本身支持 UTF-8。但经过 QClaw 管道层时,编码不统一就爆了。
修复
1. 删掉 mcp_client.py 里的 stdout 重定向
# ❌ 删掉
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
2. 用环境变量控制编码
PowerShell 调脚本前设:
$env:PYTHONIOENCODING = 'utf-8'
python mcp_client.py read_table 7
修复后
Python 层和 QClaw 管道层都走 UTF-8 → 不乱。
TABLE OK: 2 rows x 3 cols
Row 0: ['打赏。', '啊实打实', '发撒']
PAGE OK: 24 items
测阿三大苏打
原则
不要让脚本内部改 stdout 编码。 用环境变量 PYTHONIOENCODING 统一管。两边对上就不乱。
相关
- 25:word-mcp-live —— 表格踩坑与图片查看能力
- 34:COM 光标定表
- 35:COM 粘贴文档块