Mahela Munasinghe
Mahela Munasinghe

Reputation: 81

How to detect flash drive plug-in in Windows using Python?

I want to make my Windows computer run a Python script when it detects that a flash drive which has a particular name (for example "My drive") has been plugged in.

How can I achieve this?

Should I use some tool in Windows or is there a way to write another Python script to detect the presence of a flash drive as soon as it is plugged in? (I'd prefer it if the script was on the computer.)

(I'm a programming newbie.. )

Upvotes: 8

Views: 13510

Answers (4)

Free Pyhon Code
Free Pyhon Code

Reputation: 1

import subprocess

out = subprocess.check_output('wmic logicaldisk get  DriveType, caption', shell=True)

for drive in str(out).strip().split('\\r\\r\\n'):
    if '2' in drive:
        drive_litter = drive.split(':')[0]
        drive_type = drive.split(':')[1].strip()
        #print(drive_litter, drive_type)
        if drive_type == '2':
            print('Removable disk detected')

Upvotes: 0

mellow-yellow
mellow-yellow

Reputation: 1810

Building on the "CD" approach, what if your script enumerated the list of drives, waited a few seconds for Windows to assign the drive letter, then re-enumerated the list? A python set could tell you what changed, no? The following worked for me:

# building on above and http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python
import string
from ctypes import windll
import time
import os

def get_drives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1
    return drives


if __name__ == '__main__':
    before = set(get_drives())
    pause = raw_input("Please insert the USB device, then press ENTER")
    print ('Please wait...')
    time.sleep(5)
    after = set(get_drives())
    drives = after - before
    delta = len(drives)

    if (delta):
        for drive in drives:
            if os.system("cd " + drive + ":") == 0:
                newly_mounted = drive
                print "There were %d drives added: %s. Newly mounted drive letter is %s" % (delta, drives, newly_mounted)
    else:
        print "Sorry, I couldn't find any newly mounted drives."

Upvotes: 5

UltraInstinct
UltraInstinct

Reputation: 44444

Though you can use a similar method as 'inpectorG4dget' suggested but that will be a lot inefficient.

You need to use Win API for this. This page might be of use to you: Link

And to use Win API's in python check this link out: Link

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 113955

Well, if you're on a Linux distribution, then this question on SO would have the answer.

I can think of a round-about (not elegant) solution for your problem, but at the very least it would WORK.

Every time you insert your flash drive into a USB port, the Windows OS assigns a drive letter to it. For the purposes of this discussion, let's call that letter 'F'.

This code looks to see if we can cd into f:\. If it is possible to cd into f:\, then we can conclude that 'F' has been allocated as a drive letter, and under the assumption that your flash drive always gets assigned to 'F', we can conclude that your flash drive has been plugged in.

import os
def isPluggedIn(driveLetter):
    if os.system("cd " +driveLetter +":") == 0: return True
    else: return False

Upvotes: 3

Related Questions