Skip to content

截图捕获中的 UTF-8 编码错误 #224

@yueweicode

Description

@yueweicode

System Info / 系統信息

执行涉及截图捕获的任务时,程序会失败并显示:
UnicodeEncodeError: 'utf-8' codec can't encode characters in position X-Y: surrogates not allowed

Who can help? / 谁可以帮助到您?

No response

Information / 问题信息

  • The official example scripts / 官方的示例脚本
  • My own modified scripts / 我自己修改的脚本和任务

Reproduction / 复现过程

复现步骤

  1. 运行 python main.py
  2. 进入交互式模式
  3. 输入任何需要屏幕交互的任务(例如 "打开qq,发消息给老李 项目做得怎么样了")
  4. 观察执行过程中的 UnicodeEncodeError 错误

根本原因

在 phone_agent/adb/screenshot.py 中, subprocess.run() 对生成二进制输出的 ADB 命令使用了 text=True 参数:

  • adb shell screencap -p /sdcard/tmp.png 会产生二进制 PNG 数据
  • adb pull /sdcard/tmp.png temp_path 处理二进制文件传输
    使用 text=True 会导致 Python 尝试对二进制数据进行 UTF-8 编码,当遇到代理字符时会失败。

解决方案

修改 screenshot.py ,对二进制命令使用 text=False ,并仅对文本输出进行适当解码:

# 执行截图命令(二进制模式)
result = subprocess.run(
    adb_prefix + ["shell", "screencap", "-p", "/sdcard/tmp.png"],
    capture_output=True,
    text=False,  # 截图使用二进制模式
    timeout=timeout,
)

# 检查截图失败情况(使用错误处理进行解码)
output = (result.stdout + result.stderr).decode('utf-8', errors='replace')

# 拉取截图(二进制模式)
subprocess.run(
    adb_prefix + ["pull", "/sdcard/tmp.png", temp_path],
    capture_output=True,
    text=False,  # 文件传输使用二进制模式
    timeout=5,
)

Expected behavior / 期待表现

修复方式如上

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions