views:

397

answers:

2

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

+1  A: 

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
inspectorG4dget
But the drive won't always be assigned to the same letter. How can I account for that?
Mahela Munasinghe
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
+4  A: 

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

Srivatsan Iyer
This works, but requires the installation of at least one additional module
inspectorG4dget