How to detect a new usb device is connected on python

左心房为你撑大大i 提交于 2019-12-02 18:24:26

问题


I wanna 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?


回答1:


this is operating system dependent

in linux you can use pyudev for this :

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/

source code is in http://pyudev.readthedocs.io/en/v0.14/api/monitor.html, see the receive_device() function

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




回答2:


An alternative (also for windows) could be to use PySerial. You could use a QTimer (from PyQt) instead of the while-loop, either in a singlethreaded or multithreaded configuration. A basic example (without QTimer or threading):

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)


来源:https://stackoverflow.com/questions/47495206/how-to-detect-a-new-usb-device-is-connected-on-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!