[Python] HWID를 이용한 Serial Port 찾기
특정 HWID를 이용하여 Serial Port 번호 찾기 Code 입니다.
주로 여러 장비들을 탈착하다보면 고정된 port에 꽂지 않고 중구난방 꽂아버리는 저 같은 친구들 (...)이 있기 때문에,
아무데나 꽂아도 해당 장비의 port를 찾아주는 Code를 작성해봤습니다.
https://github.com/lucyk4t/serialmodule
SerialModule.py : 실제 동작하는 모듈 클래스
PySerial.py : main 클래스
[Main Class]
import serialmodule as sm
def main():
SerialModule = sm.SerialPortControl()
device = SerialModule.getPort()
SerialModule.serialObjectCreate(device)
if __name__ == '__main__':
main()
[Module Class]
import serial as ser
import serial.tools.list_ports as listport
import re
class SerialPortControl:
def __init__(self):
self.regex_vplogVID = re.compile(r'{\S+}_VID')
def getPort(self):
try:
for port in listport.comports():
if re.findall(self.regex_vplogVID, port.hwid):
return port.device
break
else: # no break encountered
raise ValueError("COM port not found")
except Exception as e:
print(e)
def serialObjectCreate(self, device):
try:
serialobj = ser.Serial(device, baudrate=9600, bytesize=ser.EIGHTBITS, parity=ser.PARITY_NONE)
except Exception as e:
print(e)