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?