You need to enable JavaScript to run this app. Python运行microbit消息转发代码时报NoneType无split属性的AttributeError错误
优惠活动
大模型
产品
解决方案
定价
更多

Python运行microbit消息转发代码时报NoneType无split属性的AttributeError错误

microbit无线电转发代码触发 AttributeError: 'NoneType' object has no attribute 'split' 报错

我基于microbit库编写了无线电消息转发功能代码,运行时触发上述报错。代码需求为:接收到消息后转发到对应目标节点,同时将消息转发到指定监听频道的间谍节点,该代码为Grok平台课程作业内容。

原代码

from microbit import *
import radio

radio.on()  
radio.config(channel=8)
routing_table = { 'Alice': 8, 'Bob': 10, 'Charlie': 15 }
spy = 60

def forward_message(msg):
    source, destination, payload = msg.split(':')
    radio.config(channel=10)
    radio.send(msg)

def forward_to_spy(msg):
    source, destination, payload = msg.split(':')
    radio.config(channel=60)
    radio.send(msg)

while True:
    msg = radio.receive()
    if msg:
        msg = radio.receive()
        forward_message(msg)
        forward_to_spy(msg)
        ack = radio.receive()
        while ack is None:
            ack = radio.receive()
        forward_message(ack)

报错原因与逻辑问题排查

触发报错的直接原因是空值(None)传入了split()方法,具体代码逻辑问题如下:

  • 最直接触发报错的逻辑错误:进入if msg判断分支后,重复调用了一次radio.receive()覆盖了原本有效的msg值,这次无新消息的receive调用会返回None,后续msg.split()自然触发空值报错
  • 路由表完全未生效:定义的routing_table没有参与频道切换逻辑,forward_message中硬编码了频道10,不符合转发到不同目标节点的需求
  • 频道切换后未恢复:每次转发后修改了无线电频道,没有切回默认的8频道,后续无法正常接收主频道消息
  • 无消息格式校验:传入split()前没有校验消息是否符合来源:目的地:载荷的格式,不符合格式的消息也会触发解析错误
  • 确认消息(ack)处理逻辑不合理:死等ack的循环没有超时机制,出现丢包时会直接卡死;且ack同样会被传入无校验的解析逻辑,也可能触发同类报错

修复后代码

from microbit import *
import radio

# 配置主监听频道
radio.on()
radio.config(channel=8)
# 路由表:目标节点对应转发频道
routing_table = {'Alice': 8, 'Bob': 10, 'Charlie': 15}
# 间谍节点监听频道
spy_channel = 60

def forward_message(msg):
    # 先校验消息格式,避免空值/格式错误触发解析报错
    if not msg or ':' not in msg:
        return
    # 限制最多拆分2次,避免载荷内的冒号干扰解析
    source, destination, payload = msg.split(':', 2)
    # 从路由表取对应目标的转发频道,取不到则跳过
    target_channel = routing_table.get(destination)
    if not target_channel:
        return
    radio.config(channel=target_channel)
    radio.send(msg)
    # 切回主频道,保证后续正常接收
    radio.config(channel=8)

def forward_to_spy(msg):
    if not msg or ':' not in msg:
        return
    radio.config(channel=spy_channel)
    radio.send(msg)
    # 切回主频道
    radio.config(channel=8)

while True:
    msg = radio.receive()
    if not msg:
        sleep(100)
        continue
    # 直接使用首次接收到的有效消息,不要重复调用receive
    forward_message(msg)
    forward_to_spy(msg)
    # 接收ack逻辑:增加1秒超时,避免死等
    ack = None
    start_time = running_time()
    while running_time() - start_time < 1000:
        ack = radio.receive()
        if ack:
            break
    if ack:
        forward_message(ack)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 12:57:01