【问题标题】:Find USB serial port with Python script用 Python 脚本查找 USB 串口
【发布时间】:2019-09-08 15:30:09
【问题描述】:

我正在尝试用 python 编写一个脚本,以便在 1 秒内找到插入笔记本电脑的 USB 串行适配器的 COM 号。 我需要的是隔离 COMx 端口,以便我可以显示结果并使用该特定端口打开腻子。你能帮我解决这个问题吗?

到目前为止,我已经在批处理/powershell 中编写了一个脚本,并且我正在获取此信息,但我无法分离 COMx 端口的文本,因此我可以使用串行参数调用 putty 程序。 我也可以通过 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

【问题讨论】:

    标签: python windows serial-port usb


    【解决方案1】:

    这是@MacrosG 的后续回答
    我尝试了一个带有设备属性的最小示例

    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)
    
    

    【讨论】:

    • 不错!是的!现在唯一要做的就是获取括号中的 COMx 信息!顺便说一句,你知道我怎么能得到这个吗?
    【解决方案2】:

    如果 Python 说字符串不一样,我敢说它们很可能不一样。

    你可以比较:

    if  "USB Serial Port" in devs[i]:
    

    那么您应该能够找到的不是一个完整的字母匹配,而是一个包含 USB 端口的匹配。

    不需要使用 numpy,devs 已经是一个列表,因此可以迭代。

    【讨论】:

      【解决方案3】:

      如果你想用正则表达式做到这一点:

      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
      

      【讨论】:

        【解决方案4】:

        非常感谢大家,尤其是 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)
        

        谢谢大家!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多