如何检测新的USB设备已连接到Python上



我想做一些会在后台运行的东西,只有在计算机检测到新设备连接后,代码的其余部分才能运行,是否有任何优雅的方法来执行此类操作?

这是操作系统依赖

在Linux中您可以使用pyudev

几乎公开了完整的libudev功能。您可以:

  • 枚举设备,由特定标准(Pyudev.Context)过滤
  • 查询设备信息,属性和属性,
  • Monitor Devices ,无论是与背景线程,或在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/02/24/displaying-usb-devices-usb-devices-using-wmi/设备管理器信息)或python绑定,例如https://pypi.python.org/pypi/infi.devicemanager

替代方案(也适用于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)

您可以使用OS库查看连接到计算机的所有驱动器。以下代码将告诉您驱动器名称以及是否已连接或断开连接。此外,当连接驱动器时,代码将执行函数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

的3.8制作的。

如果插入

,可以使用WMIC检测USB
#coding:utf-8
import os
os.system("color")
Usb = os.popen("wmic logicaldisk where drivetype=2 get description ,deviceid ,volumename").read()
print(Usb)
if Usb.find("DeviceID") != -1:
    print("33[1;32mUsb is plugged")
    input("")
else:
    print("33[0;31mUsb is not plugged")
    input("")

您可以将pyudev

之类的东西一起使用
from pyudev import Context, Monitor
ctx = Context()
    monitor = Monitor.from_netlink(ctx)
    monitor.filter_by(subsystem='usb')
    for device in iter(monitor.poll, None):
        if device.action == 'add':
            print("Yay, we have a connected device")

我还开发了一个python脚本,该脚本会聆听特定设备并在连接时执行操作,例如:

pip install udev_monitor
udev_monitor.py --devices 0665:5161 --filters=usb --action /root/some_script.sh

您可以在此处找到完整的资源

相关内容

  • 没有找到相关文章

最新更新