You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python pyserial多线程异常:主线程未执行问题排查求助

问题原因及解决方法

你的代码核心错误出在线程初始化的语句上:

x = threading.Thread(target = monitor_bmc_console(), daemon=True)

这里你直接调用了monitor_bmc_console()函数(加了括号),这会导致主线程在创建线程之前就直接进入该函数的无限循环,完全阻塞了后续主线程代码的执行,自然看不到inside main thread的输出。

修正方案

把target参数改为传入函数对象(去掉括号):

x = threading.Thread(target=monitor_bmc_console, daemon=True)

完整修正代码

import serial
import serial.threaded
import time
import threading

PORT = 'loop://'

def monitor_bmc_console():
    class TestLines(serial.threaded.LineReader):
        def __init__(self):
            super(TestLines, self).__init__()
            self.received_lines = []

        def handle_line(self, data):
            self.received_lines.append(data)

    ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1)
    with serial.threaded.ReaderThread(ser, TestLines) as protocol:
        while True:
            protocol.write_line('hello')
            time.sleep(2)
            print(protocol.received_lines)


x = threading.Thread(target=monitor_bmc_console, daemon=True)
x.start()

while True:
    print('inside main thread')
    time.sleep(1)

修正后,线程会独立运行monitor_bmc_console函数,主线程则正常执行自身的循环逻辑,你就能同时看到两种输出并行打印了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:06:03