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

Python实现持续监控串口(串口未打开时保持脚本运行)求助

Fixing Persistent Serial Port Monitoring in Python

Hey there! Let's fix your serial port monitoring script so it keeps running even when the port isn't available or access is denied. The main issue with your current code is that you're trying to open the port outside the try block, so if that fails, the exception isn't caught properly. Plus, there's no retry logic—once it hits an error, the script just exits.

Here's a revised version that handles retries and keeps the script alive:

import serial
import time

z1baudrate = 9600
z1port = 'COM4'

def monitor_serial_port():
    while True:
        z1serial = None
        try:
            # Try to open the serial port
            z1serial = serial.Serial(port=z1port, baudrate=z1baudrate, timeout=1)
            print(f"Successfully opened {z1port}")
            
            # Keep reading while the port is open
            while z1serial.is_open:
                size = z1serial.inWaiting()
                if size:
                    data = z1serial.read(size)
                    res = data.decode("utf-8")
                    print(res)
                else:
                    # Optional: Remove this print if you don't want constant "no data" messages
                    # print("Data not reading")
                    time.sleep(1)
                    
        except serial.SerialException as e:
            print(f"Error accessing {z1port}: {str(e)}")
            print("Retrying in 5 seconds...")
            time.sleep(5)  # Wait before retrying
        finally:
            # Make sure we close the port if it was opened
            if z1serial and z1serial.is_open:
                z1serial.close()
                print(f"Closed {z1port}")

if __name__ == "__main__":
    monitor_serial_port()

Key Improvements:

  • Outer retry loop: The outer while True ensures the script never exits—if it hits an error (like port not found or access denied), it waits and tries again.
  • Port initialization inside try block: All errors during port opening are now caught, so the script doesn't crash immediately.
  • Proper port cleanup: The finally block guarantees the port is closed if it was opened, preventing resource leaks.
  • Fixed missing import: Added import time since your original code used time.sleep() without importing the module.
  • Adjustable retry delay: The 5-second wait before retrying can be changed to whatever interval works best for your use case.

内容的提问来源于stack exchange,提问作者Abdul Rahman B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:44:07