1

I want a python program that listens to USB ports and after connecting save USB path to a file:

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())
  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)
            f = open( 'path.txt', 'w' )
            f.write(newly_mounted)
            f.close()
else:
    print "Sorry, I couldn't find any newly mounted drives."

and after that in main file call it to:

import os
import time

while True:
    os.system("python test.py")
    time.sleep(1)

but it's not working correctly and when i connect USB sometimes it work and sometimes. is there any way to improve it?

wallyk
  • 56,922
  • 16
  • 83
  • 148
Natasha Sh
  • 11
  • 1
  • 2
  • Natasha, I altered the indentation to make better sense, but please check that I did not alter it beyond recognition. Also, there was a "USA" that I think was meant to be "USB" (but change it back if not). – wallyk Jul 02 '15 at 23:41

2 Answers2

0

There are some problems with your implementation:

  1. Your 'main' file calling test.py invokes it once a second, but test.py waits five seconds between before and after. I can't remember if the python system call blocks the caller - so either a) if it doesn't block then test.py is being invoked again while it is still waiting to get the after, or b) if it does block then there is a one second delay in the 'main' where changes are never seen. Fix: #2 below fixes this by not having separate programs.

  2. Because test.py determines before, waits five seconds, then determines after, THEN quits, a usb drive change could happen between a quit and a start and wouldn't be reported as a change by test.py. You need to make test.py never exit - it should set before when it starts, then check every five seconds and if after is different then update before with the new value of after, and go back to wait another five seconds. Fix: test.py should never exit - it should be 'main', or run forever in a thread.

  3. If a device is plugged in just after before has been determined, then removed before after is determined, i.e. within up to five seconds, this is never reported by test.py. Fix: may not matter, and if using polling then you have to delay some time between checks. Only real solution is to not use polling but to hook into OS event notification of drive changes, which would also be the most robust implementation...

Anyway, assuming polling is best solution your code in test.py should look something like this (note test.py never exits otherwise you could miss a change):

  before = set(get_drives())
  while true:
    time.sleep(5)
    after = set(get_drives())
    drives = after - before
    delta = len(drives)

    if (delta):
      # ...process delta
      ...
      # finally, after becomes the new before WITHOUT re-reading the drives, that will happen again in five seconds...
      before = after
  • How it's possible to run test.py in 3 threads in 3 different time something like. thread 1 in second 1 thread 2 in second 2 thread 3 in second 3 that every time something listen to USB port – Natasha Sh Jul 03 '15 at 08:03
  • I won't ask why would you want to run three threads all looking at drive states. You'll have to make the checking in test.py into a python function. This previous answer may help you http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies – DisappointedByUnaccountableMod Jul 03 '15 at 09:24
0

Hi i made this app using python refer drive-monitoring its a Event Based Approach to create reports about the Removable Drive History and file system events in drives.

Ajay Kumar K K
  • 321
  • 2
  • 7