How to detect if USB device is plugged in using python?
Asked Answered
K

3

6

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 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 crash and display this error :

import fcntl ModuleNotFoundError: No module named 'fcntl'

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

Kamat answered 1/2, 2020 at 6:26 Comment(2)
Try this #7552046Beneficial
if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100'] or vendor_id in ['USB\\VID_0930&PID_6544']: == if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100', 'USB\\VID_0930&PID_6544']:Inwardly
K
3

i solved my question and i wrote this script that allow 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))
Kamat answered 2/2, 2020 at 11:50 Comment(1)
final line (print) should be indented/part of if statement, no?Overjoy
H
0

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

code was actually taken from https://mail.python.org/pipermail/python-win32/2006-December/005406.html

Hindrance answered 1/2, 2020 at 7:49 Comment(0)
V
0

I made a Python script that listens for specific devices and executes action when connected, eg:

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.

Volotta answered 7/11, 2022 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.