Python/Mido MIDI回调函数无报错崩溃问题求助
MIDI回调函数无报错崩溃问题排查
问题描述
我是Python和MIDI处理的新手,遇到了异常情况:以下代码中的listen_input MIDI回调函数会无报错崩溃,print(2)从未执行,但程序没报明显错误。
代码
import mido import time def listen_input(message): print('input:', message) print(1) filtered_on_message = copy.copy(message) filtered_on_message.velocity = 50 output_message(filtered_on_message) print(2) inport = mido.open_input('reface CP', callback=listen_input) outport = mido.open_output('reface CP') while True: time.sleep(1)
程序输出
input: note_on channel=0 note=79 velocity=81 time=0 1 input: note_on channel=0 note=79 velocity=0 time=0 1 input: note_on channel=0 note=79 velocity=77 time=0 1 input: note_on channel=0 note=79 velocity=0 time=0 1
问题原因
你的代码存在两个明确错误,且由于mido回调的线程特性,错误不会在主线程控制台显示:
- 未导入
copy模块:执行copy.copy(message)时会触发NameError,但回调运行在独立线程中,主线程无法捕获该异常。 - 未定义
output_message函数:调用不存在的函数同样会触发NameError,同样因线程隔离无法在控制台看到报错。
mido的回调函数运行在单独的后台线程,线程内的异常不会自动传递到主线程,所以程序看起来是“无报错崩溃”,实则是回调执行到错误处就终止了,导致print(2)从未执行。
修复方案
- 补上缺失的
copy模块导入 - 实现
output_message函数(用已打开的outport发送消息) - 可选:在回调中添加异常捕获,方便后续排查问题
修复后的代码
import mido import time import copy # 导入copy模块 def output_message(msg): # 实现消息发送逻辑 outport.send(msg) def listen_input(message): # 可选:添加异常捕获 try: print('input:', message) print(1) filtered_on_message = copy.copy(message) filtered_on_message.velocity = 50 output_message(filtered_on_message) print(2) except Exception as e: print(f"回调执行出错: {e}") inport = mido.open_input('reface CP', callback=listen_input) outport = mido.open_output('reface CP') while True: time.sleep(1)
内容的提问来源于stack exchange,提问作者theredled
相关产品推荐
相关产品推荐

