8

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.. )

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

4 Answers4

5

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."
mellow-yellow
  • 1,670
  • 1
  • 18
  • 38
4

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

Community
  • 1
  • 1
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
3

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
Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 1
    But the drive won't always be assigned to the same letter. How can I account for that? – Mahela Munasinghe Dec 28 '09 at 17:32
  • That's just the thing. I can't think of a way to do that right away. But at the very least, this is a partial solution. I only posted it because there was no other solution at the time. So I figured a partial solution would be better than none at all – inspectorG4dget Dec 29 '09 at 06:42
0
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')
General Grievance
  • 4,555
  • 31
  • 31
  • 45