简体   繁体   English

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

[英]How to detect a new usb device is connected on python

I want to make something which will run on the background and only after the computer detect new device is connected the rest of the code will run, is there any elegant way to do such a thing?我想做一些在后台运行的东西,只有在计算机检测到新设备连接后,代码的 rest 才会运行,有没有什么优雅的方法来做这样的事情?

this is operating system dependent这是操作系统相关的

in linux you can use pyudev for this :在 linux 中,您可以为此使用pyudev

Almost the complete libudev functionality is exposed.几乎完整的 libudev 功能都已公开。 You can:你可以:

  • Enumerate devices, filtered by specific criteria (pyudev.Context)枚举设备,按特定条件过滤(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).监视设备,与后台线程同步和异步,或在 Qt (pyudev.pyqt4, pyudev.pyside)、glib (pyudev.glib) 和 wxPython (pyudev.wx) 的事件循环内。

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

source code is in http://pyudev.readthedocs.io/en/v0.14/api/monitor.html , see the receive_device() function源代码在http://pyudev.readthedocs.io/en/v0.14/api/monitor.html 中,查看receive_device()函数

in windows you can use the WMI ( Windows Management Instrumentation ) like in https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/ ( Python Read the Device Manager Information ) or a python binding like in https://pypi.python.org/pypi/infi.devicemanager在 Windows 中,您可以使用 WMI(Windows 管理规范),如https://blogs.msdn.microsoft.com/powershell/2007/02/24/displaying-usb-devices-using-wmi/(Python 读取设备管理器) Information ) 或 python 绑定,如https://pypi.python.org/pypi/infi.devicemanager

An alternative (also for windows) could be to use PySerial.另一种选择(也适用于 Windows)可能是使用 PySerial。 You could use a QTimer (from PyQt) instead of the while -loop, either in a singlethreaded or multithreaded configuration.您可以在单线程或多线程配置中使用QTimer (来自 PyQt)而不是while循环。 A basic example (without QTimer or threading):一个基本示例(没有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)

You can use the OS library to see all drives connected to your computer.您可以使用操作系统库查看连接到计算机的所有驱动器。 The following code will tell you the drives name and if it was connected or disconnected.以下代码将告诉您驱动器名称以及它是否已连接或断开连接。 In addition the code executes the function foo() when a drive is connected.此外,该代码在连接驱动器时执行函数 foo()。 Also, when a drive is disconnected it will execute the command ham()此外,当驱动器断开连接时,它将执行命令 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)]

This code is made for python 3.8 for windows此代码是为 windows 的 python 3.8 制作的

You can use WMIC for detecting usb if plugged如果插入,您可以使用 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("\033[1;32mUsb is plugged")
    input("")

else:
    print("\033[0;31mUsb is not plugged")
    input("")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检测何时连接了新的USB设备(即插即用) - Detect when new USB device is connected (plug'n'play) 如何使用python检测USB设备是否插入? - How to detect if USB device is plugged in using python? 使用python检测连接到USB的开关的状态 - Detect the state of a switch connected to USB with python 如何使用 python 或 ZDFFF0A7FA1A55C8C1A4966C19F6DA425 从 windows 连接 USB 设备列表 - How to get connected USB device list from windows by using python or cmd 我如何通过python从连接的设备获取USB号码端口 - how i Get usb number port from connected device via python 一个 python 脚本,在连接的计算机设备上打印 USB 字母和 USB 名称 - A python script that prints both USB letter and USB name of a usb device connected on a computer 我们可以在 python 中检测到连接到 USB 集线器的设备吗 - Can we detect devices connected to USB hub in python 当我将 python 放在树莓派中时,如何获取 usb 设备的文件目录? - How can i get file directory of usb device afer detect it when i placed in raspberry pi in python? Bash-连接USB设备时如何运行代码 - Bash - How to run code whenever USB device is connected Python / Linux-如何在插入新的USB存储设备时创建监视USB端口并打印安装点路径的脚本? - Python/Linux-How to create a script that monitor USB ports and print the mount point path when a new USB Storage Device is plugged?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM