detect if usb is plugged in python 1

detect if usb is plugged in python

import pyudev
context = pyudev.Context()
monitor = Monitor.from_netlink()
# For USB devices
# OR specifically for most USB serial devices
for action, device in monitor:
    vendor_id = device.get('ID_VENDOR_ID')
    # I know the devices I am looking for have a vendor ID of '22fa'
    if vendor_id in ['22fa']:
        print 'Detected {} for device with vendor ID {}'.format(action, vendor_id)

Here is what the above code is Doing:
1. Create a context object. This is used to create a monitor object.
2. Create a monitor object. This is used to monitor for events.
3. Filter the monitor object to only look for USB devices.
4. Loop through the monitor object and print out the action and vendor ID.

The action will be one of the following:
add – A device was added.
remove – A device was removed.
change – A device was changed.
move – A device was moved.
online – A device was brought online.
offline – A device was taken offline.

The vendor ID is the vendor ID of the device.

Similar Posts