如何检测python上连接的新usb设备

2024-04-20 15:26:21 发布

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

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


Tags: 方法代码计算机事情后台
2条回答

另一种方法(也适用于windows)可以是使用PySerial。您可以在单线程或多线程配置中使用QTimer(来自PyQt)而不是while循环。基本示例(不带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)

这取决于操作系统

在linux中,您可以使用pyudev来执行以下操作:

Almost the complete libudev functionality is exposed. You can:

  • Enumerate devices, filtered by specific criteria (pyudev.Context)
  • Query device information, properties and attributes,
  • Monitor devices, both synchronously and asynchronously with background threads, or within the event loops of Qt (pyudev.pyqt4, pyudev.pyside), glib (pyudev.glib) and wxPython (pyudev.wx).

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

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

在windows中,您可以使用WMI(windows管理规范)如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

相关问题 更多 >