如何使用Python检测Windows中的闪存驱动器插入?
我想让我的Windows电脑在检测到一个特定名称的闪存驱动器(比如“我的驱动器”)插入时,自动运行一个Python脚本。
我该怎么做呢?
我应该在Windows中使用某个工具,还是可以写另一个Python脚本来检测闪存驱动器一插入就能被发现?(我更希望这个脚本是在电脑上的。)
(我还是个编程新手……)
4 个回答
3
好吧,如果你使用的是Linux系统,那么在StackOverflow上有一个问题可以找到答案。
我可以想到一个曲线救国(虽然不太优雅)的解决办法,但至少它是可行的。
每次你把闪存驱动器插入USB接口时,Windows系统都会给它分配一个驱动器字母。为了方便讨论,我们就把这个字母叫做'F'。
这段代码会检查我们是否可以进入f:\
这个目录。如果可以进入f:\
,那么我们就可以得出结论,'F'已经被分配为驱动器字母,并且假设你的闪存驱动器总是被分配为'F',那么我们就可以确认你的闪存驱动器已经插入了。
import os
def isPluggedIn(driveLetter):
if os.system("cd " +driveLetter +":") == 0: return True
else: return False
5
在“CD”方法的基础上,如果你的脚本先列出所有的驱动器,然后等几秒钟让Windows给这些驱动器分配字母,再重新列出一次驱动器的列表,这样会怎么样呢?你可以用Python的集合来看看有什么变化,对吧?下面的代码对我来说是有效的:
# building on above and http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python
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."