How to detect a new usb device is connected on python

Viewed 24836

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?

4 Answers

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. Also, when a drive is disconnected it will execute the command 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

You can use WMIC for detecting usb if plugged

#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("")
Related