Which USB to COM port is the most recent one?


How many times did you find yourself looking for Windows Control Panel and wondering which is the most recent plugged USB to SERIAL com port? Well simple and clean Python script comes very handy for this task.

Just start a script and plug in new device – new com port will be displayed with minimal lag. This also gives great opportunity to run production scripts to flash new firmware or automate other tasks.

import sys, re
import subprocess
import time
import serial.tools.list_ports

def grep(regexp):
for port, desc, hwid in serial.tools.list_ports.comports():
if re.search(regexp, port, re.I) or re.search(regexp, desc) or re.search(regexp, hwid):
yield port, desc, hwid

# Discover all COM ports and show them
port_list_initial = serial.tools.list_ports.comports()
for port, desc, hwid in port_list_initial:
print('-', port, desc)

print('\nWaiting for new USB to SERIAL device to be plugged in...\n')

# Wait for new device to be plugged in and show it
while True:
port_list_poll = serial.tools.list_ports.comports()

for p in port_list_poll:
if p not in port_list_initial:
print('-', p)
input('\nAll done, press enter to quit')
time.sleep(0.5) # Don't poll too often

Also code is uploaded to GitHub

Leave a reply

Your email address will not be published.