它在python中有用吗?

2024-05-19 01:14:34 发布

您现在位置:Python中文网/ 问答频道 /正文

import serial as ser
import serial.tools.list_ports as listport
import re

try:
    # VID regex
    regex_vplogVID = re.compile(r'{\S+}_VID')

    # I want to find COM port by using specific hwid
    port_device = [n.device for n in listport.comports() if re.findall(regex_vplogVID, n.hwid)]

    vplogserial = ser.Serial(port_device[0])

except Exception as e:
    print(e)

实际上,我是使用python的新手程序员。 我想找到端口使用唯一的hwid,但我认为列表理解是不合适的,因为端口将返回一个。你知道吗

我使用的是简单的for循环代码吗? 请分享您的意见。:)谢谢你的阅读。你知道吗


Tags: 端口importreforportdeviceasserial
2条回答

我会使用for循环,如果只是因为一旦找到唯一的设备,就可以提前停止迭代。你知道吗

for n in listport.comports():
    if re.findall(regex_vplogVID, n.hwid):
        vplogserial = ser.Serial(n.device)
        break

如果确实只有一个匹配项,不要使用列表。相反,在找到匹配项后使用普通for循环和break:这样就可以保证只有一个匹配项:

# I want to find COM port by using specific hwid  
regex_vplogVID = re.compile(r'{\S+}_VID')  
port_device = None
for port in listport.comports():
    if re.findall(regex_vplogVID, port.hwid):
       port_device = port.device
       break

额外的好处:如果你想超越这一点,如果没有匹配的话,你可以使用for else习语,但这是一个不太常用的习语,经常会让人困惑:

# I want to find COM port by using specific hwid 
regex_vplogVID = re.compile(r'{\S+}_VID')   
for port in listport.comports():
    if re.findall(regex_vplogVID, port.hwid):
       port_device = port.device
       break
else:  # no break encountered
    raise ValueError("COM port not found")
# No need now to have a default of `None` and check for it
vplogserial = ser.Serial(port_device[0])

相关问题 更多 >

    热门问题