Dev Dj
Dev Dj

Reputation: 169

How can I detect if a USB device is plugged in using Python?

I want to create a script that detects once the USB drive is plugged into the computer and for now just to print in the cmd detect.

Note I am using Windows. After my search, I found that I need to use the pyudev package in order to communicate with serial ports, and I need to know the vendor ID of the USB device.

I tried to wrote the below code:

import pyudev

context = pyudev.Context()
monitor = Monitor.from_netlink()

# For USB devices
monitor.filter_by(subsystem='usb')

# OR specifically for most USB serial devices
monitor.filter_by(subsystem='tty')
for action, device in monitor:
    vendor_id = device.get('ID_VENDOR_ID')

    if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100'] or vendor_id in ['USB\\VID_0930&PID_6544']:
        print ('Detected {0} for device with vendor ID {1}'.format(action, vendor_id))

But the system crashes and displays this error:

import fcntl ModuleNotFoundError: No module named 'fcntl'

I think 'fcntl' works only on Ubuntu, because I tried to install the package but it didn't exist.

Upvotes: 6

Views: 9970

Answers (3)

Orsiris de Jong
Orsiris de Jong

Reputation: 3016

I made a Python script that listens for specific devices and executes an action when connected, e.g.:

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

You can find the full sources here.

Of course, using udev, this only works for Linux.

Upvotes: 0

Dev Dj
Dev Dj

Reputation: 169

I solved my question, and I wrote this script that allows me to detect the last removable device that is plugged in.

Code:

import win32api
import win32file

# Returns a list containing letters from removable drives
drive_list = win32api.GetLogicalDriveStrings()
drive_list = drive_list.split("\x00")[0:-1]  # The last element is ""
for letter in drive_list:
    if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE:# check if the drive is of type removable
print("list drives: {0}".format(letter))

Upvotes: 3

pravin thokal
pravin thokal

Reputation: 1

Try this one out:

import win32file

def locate_usb():
    drive_list = []
    drivebits = win32file.GetLogicalDrives()
    for d in range(1, 26):
        mask = 1 << d
        if drivebits & mask:
            # Here if the drive is at least there
            drname = '%c:\\' % chr(ord('A') + d)
            t = win32file.GetDriveType(drname)
            if t == win32file.DRIVE_REMOVABLE:
                drive_list.append(drname)
    return drive_list

The code was actually taken from [python-win32] List of drives / removable drives.

Upvotes: 0

Related Questions