我正在尝试用python编写脚本,因此我可以在1秒钟内找到插入笔记本电脑的USB串行适配器的COM号。 我需要隔离COMx端口,以便显示结果并使用该特定端口打开腻子。你能帮我吗?
直到现在,我已经用批处理/ powershell编写了一个脚本,并且获得了此信息,但是我仍无法分隔COMx端口的文本,因此我可以使用串行参数调用腻子程序。 我也可以通过Python找到端口,但无法将其与字符串隔离。
import re # Used for regular expressions (unused)
import os # To check that the path of the files defined in the config file exist (unused)
import sys # To leave the script if (unused)
import numpy as np
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
print ('Type of Devs: ',type(devs))
myarray = ([])
myarray =np.array(devs)
print ('Type of thing: ',type(myarray))
match = '<USB Serial Port (COM6)>' (custom match. the ideal would be "USB Serial Port")
i=0
#print (myarray, '\n')
while i != len(devs):
if match == myarray[i]:
print ('Found it!')
break
print ('array: ',i," : ", myarray[i])
i = i+1
print ('array 49: ', myarray[49]) (here I was checking what is the difference of the "element" inside the array)
print ('match : ', match) (and what is the difference of what I submitted)
print ('end')
我期望if match == myarray [i]可以找到两个元素,但是由于某种原因,它找不到。让我感到这两个不一样。
谢谢您的帮助!
===更新=== 完整的脚本可以在这里找到 https://github.com/elessargr/k9-serial
答案 0 :(得分:1)
这是@MacrosG的后续回答
我尝试了一个带有Device
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
for d in devs:
if "USB" in d.description :
print(d.description)
答案 1 :(得分:0)
如果Python说的字符串不一样,我敢说很可能不是。
您可以与以下内容进行比较:
if "USB Serial Port" in devs[i]:
这时,您应该找不到一个完整的字母匹配项,而是一个包含USB端口的匹配项。
不需要使用numpy,devs
已经是列表,因此可以迭代。
答案 2 :(得分:0)
如果要使用正则表达式执行此操作:
def main():
from infi.devicemanager import DeviceManager
import re
device_manager = DeviceManager()
device_manager.root.rescan()
pattern = r"USB Serial Port \(COM(\d)\)"
for device in device_manager.all_devices:
try:
match = re.fullmatch(pattern, device.friendly_name)
except KeyError:
continue
if match is None:
continue
com_number = match.group(1)
print(f"Found device \"{device.friendly_name}\" -> com_number: {com_number}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
输出:
Found device "USB Serial Port (COM3)" -> com_number: 3
答案 3 :(得分:0)
自从我采用他的解决方案以来,非常感谢所有人,尤其是bigdataolddriver
最后一件事!
for d in devs:
if "USB Serial Port" in d.description :
str = d.__str__()
COMport = str.split('(', 1)[1].split(')')[0]
i=1
break
else:
i=0
if i == 1:
print ("I found it!")
print(d.description, "found on : ", COMport)
subprocess.Popen(r'"C:\Tools\putty.exe" -serial ', COMport)
elif i ==0:
print ("USB Serial Not found \nPlease check physical connection.")
else:
print("Error")
有什么想法如何将COMport作为参数传递给putty.exe?
=====更新=====
if i == 1:
print ("I found it!")
print(d.description, "found on : ", COMport)
command = '"C:\MyTools\putty.exe" -serial ' + COMport
#print (command)
subprocess.Popen(command)
谢谢大家!