简体   繁体   中英

How to implement a Python USB device listener for windows

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?

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, ie 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

嗨,我使该应用程序使用python引用驱动器监控其基于事件的方法来创建有关驱动器中可移动驱动器历史记录和文件系统事件的报告。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM