如何检测RS232串口连接的打印机是否断开连接?
Your existing approaches have critical limitations:
- The
serial.read()method blocks indefinitely if the printer sends no data, and Windows often keeps COM ports registered even after physical disconnection. - WMI's
Win32_SerialPortonly lists ports recognized by the OS, not whether a printer is actively connected and responsive on that port.
Here are three reliable methods to detect printer disconnections:
Method 1: Monitor Serial Control Lines (DTR/CTS/RTS)
Most RS232 printers maintain active control signals (like DTR or CTS) when connected. Poll these signals periodically to check connection status.
import serial import time def check_printer_connection(port='COM1'): try: ser = serial.Serial(port, timeout=1) # Check DTR line (adjust based on your printer's specs) is_connected = ser.dtr ser.close() return is_connected except serial.SerialException: # Port not recognized (likely disconnected) return False # Poll every 5 seconds while True: if not check_printer_connection('COM1'): print("Printer disconnected!") else: print("Printer connected") time.sleep(5)
Note: Verify which control line your printer uses (DTR, CTS, RTS) via its manual.
Method 2: Send a Test Command and Validate Response
Send a known command to the printer (e.g., status query) and check for a valid response. This ensures the printer is not just connected but functional.
import serial import time def test_printer_response(port='COM1', baudrate=9600): try: ser = serial.Serial(port, baudrate=baudrate, timeout=2) # Example: Epson ESC/POS status query command ser.write(b'\x10\x04\x01') response = ser.read(10) ser.close() # Check for non-empty response (adjust based on your printer's expected output) return len(response) > 0 except (serial.SerialException, TimeoutError): return False while True: if not test_printer_response('COM1'): print("Printer disconnected or unresponsive!") time.sleep(5)
Look up your printer's specific command set (e.g., ESC/POS for Epson, StarPRNT for Star Micronics) for accurate test commands.
Method 3: Listen for Windows Device Removal Events
Use pywin32 to monitor system events triggered when an RS232 device is physically disconnected.
import win32gui import win32con import win32api import win32com.client import time class DeviceMonitor: def __init__(self): # Create a hidden window to receive device events self.hwnd = win32gui.CreateWindowEx(0, "STATIC", "", 0, 0, 0, 0, 0, 0, 0, 0) win32api.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, self.window_proc) # Set up WMI watcher for serial port removal self.wmi = win32com.client.Dispatch("WbemScripting.SWbemLocator").ConnectServer() self.watcher = self.wmi.ExecNotificationQueryAsync( "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_SerialPort'" ) self.watcher.OnObjectReady = self.on_device_removed def window_proc(self, hwnd, msg, wparam, lparam): if msg == win32con.WM_DEVICECHANGE and wparam == win32con.DBT_DEVICEREMOVECOMPLETE: print("Serial device disconnected!") return win32gui.DefWindowProc(hwnd, msg, wparam, lparam) def on_device_removed(self, obj, ctx): port = obj.TargetInstance.DeviceID print(f"Printer on {port} disconnected!") def run(self): while True: win32gui.PumpWaitingMessages() time.sleep(0.1) if __name__ == "__main__": monitor = DeviceMonitor() monitor.run()
This method detects physical disconnections in real time without polling.
Key Tips:
- Control line monitoring is lightweight but depends on your printer's signal behavior.
- Test commands are the most reliable way to confirm the printer is functional, not just connected.
- Device event monitoring works best for sudden physical disconnections.
内容的提问来源于stack exchange,提问作者José Timaure

