You need to enable JavaScript to run this app. Python Behave串口测试出现latin-1编码UnicodeEncodeError报错如何处理
优惠活动
大模型
产品
解决方案
定价
更多

Python Behave串口测试出现latin-1编码UnicodeEncodeError报错如何处理

问题根因

你写的串口读写代码本身没有问题,已经正确使用了UTF-8编解码。报错的触发点是Behave框架的输出格式化模块默认使用latin-1编码向终端/日志写入内容,你串口解码时用replace参数生成的乱码替换字符\ufffd不属于latin-1的编码范围,因此写入输出流时触发报错。

解决方法

方法1:临时设置系统环境变量(最快捷)

运行behave命令前先设置PYTHONUTF8环境变量为1,强制Python所有标准流使用UTF-8编码:
Linux/macOS终端执行:

export PYTHONUTF8=1
behave <你的测试参数>

Windows cmd执行:

set PYTHONUTF8=1
behave <你的测试参数>

Windows PowerShell执行:

$env:PYTHONUTF8=1
behave <你的测试参数>

方法2:修改Behave运行时的输出流编码

在项目根目录下新建environment.py文件(如果已有就直接在文件中添加以下内容):

import sys
from behave.formatter import _registry
from behave.formatter.plain import PlainFormatter

# 强制所有输出流使用UTF-8编码
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')

# 自定义安全格式化器处理不可编码字符
class UTF8SafePlainFormatter(PlainFormatter):
    def result(self, step):
        if step.error_message:
            # 提前处理错误信息中的不可编码字符
            step.error_message = step.error_message.encode('utf-8', 'replace').decode('utf-8')
        super().result(step)

# 注册自定义格式化器替换默认的plain格式化器
_registry.register("plain", UTF8SafePlainFormatter)

方法3:修改串口读逻辑提前过滤特殊字符

如果不想修改Behave相关配置,可以在读串口输出时直接把\ufffd替换为latin-1支持的普通占位符:

def read_output(self):
    line = self.ser.readline()
    converted_line = line.decode("UTF-8", "replace").replace('\n', '')
    # 新增一行替换特殊字符,避免Behave输出时报错
    converted_line = converted_line.replace('\ufffd', '?')
    return converted_line

内容的提问来源于stack exchange,提问作者m4ng0o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 04:48:03