简体   繁体   中英

how to detect multiple USB ports and read data from USB using python

I have been able to detect whenever a flash drive is inserted. However, (silly as it sounds) having trouble to detect if multiple USB be inserted. Also, i am having difficulty in writing the code to read to data from it(them). Can someone please help? Thanks, in advance :) PS my system is windows 8 64 bit The whole thing is about detecting signals that i will pick from sensors.

here is the code to detect USB

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

我在计算机上尝试了您的代码。它运行正常。我的系统是win7 64bit pro。

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