【问题标题】:How to detect a new usb device is connected on python如何检测python上连接了新的usb设备
【发布时间】:2017-11-26 10:38:48
【问题描述】:

我想做一些在后台运行的东西,只有在计算机检测到新设备连接后,其余代码才会运行,有没有什么优雅的方法来做这样的事情?

【问题讨论】:

标签: python usb pyudev


【解决方案1】:

这取决于操作系统

在 linux 中,您可以使用 pyudev

几乎完整的libudev 功能都暴露了。你可以:

  • 枚举设备,按特定条件过滤 (pyudev.Context)
  • 查询设备信息、属性和属性,
  • 监控设备,与后台线程同步和异步,或者在 Qt 的事件循环中(pyudev.pyqt4, pyudev.pyside)、glib (pyudev.glib) 和 wxPython (pyudev.wx)。

https://pyudev.readthedocs.io/en/latest/

源码在http://pyudev.readthedocs.io/en/v0.14/api/monitor.html,见receive_device()函数

在 Windows 中,您可以使用 WMI (Windows Management Instrumentation),如 https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/ (Python Read the Device Manager Information) 或 python 绑定,如 https://pypi.python.org/pypi/infi.devicemanager

【讨论】:

    【解决方案2】:

    另一种选择(也适用于 Windows)可能是使用 PySerial。您可以在单线程或多线程配置中使用 QTimer(来自 PyQt)而不是 while-loop。一个基本示例(没有QTimer 或线程):

    import time
    from serial.tools import list_ports  # pyserial
    
    def enumerate_serial_devices():
        return set([item for item in list_ports.comports()])
    
    def check_new_devices(old_devices):
        devices = enumerate_serial_devices()
        added = devices.difference(old_devices)
        removed = old_devices.difference(devices)
        if added:
            print 'added: {}'.format(added)
        if removed:
            print 'removed: {}'.format(removed)
        return devices
    
    # Quick and dirty timing loop 
    old_devices = enumerate_serial_devices()
    while True:
        old_devices = check_new_devices(old_devices)
        time.sleep(0.5)
    

    【讨论】:

      【解决方案3】:

      您可以使用操作系统库来查看连接到您的计算机的所有驱动器。以下代码将告诉您驱动器名称以及它是连接还是断开连接。此外,当驱动器连接时,代码会执行函数 foo()。此外,当驱动器断开连接时,它将执行命令 ham()

      import os.path
      
      
      def diff(list1, list2):
          list_difference = [item for item in list1 if item not in list2]
          return list_difference
      
      
      def foo():
          print("New dive introduced")
      
      
      def ham():
          print("Drive disconnected")
      
      
      dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]
      print(drives)
      while True:
          uncheckeddrives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]
          x = diff(uncheckeddrives, drives)
          if x:
              print("New drives:     " + str(x))
              foo()
          x = diff(drives, uncheckeddrives)
          if x:
              print("Removed drives: " + str(x))
              ham()
          drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]
      
      

      此代码是为 windows 的 python 3.8 编写的

      【讨论】:

      • 此脚本可能会错过更改,因为它在检查后使用新数据更新了驱动器变量,最后一行应为 drive = uncheckeddrives 以防止这种情况发生。
      • 此代码正在使用繁忙的等待 - 资源效率不高...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多