# 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."
虽然你可以使用类似于“inpectorG4dget”建议的方法,但这将是非常低效的。
您需要为此使用Win API。此页可能对您有用:Link
要在python中使用Win API,请查看以下链接:Link
在“CD”方法的基础上,如果您的脚本枚举了驱动器列表,等待了几秒钟Windows分配驱动器号,然后重新枚举了列表,会怎么样?一套Python可以告诉你发生了什么变化,不是吗?以下对我有效:
好吧,如果您使用的是Linux发行版,那么this question就有了答案。
我可以为你的问题想出一个全面的(不优雅的)解决方案,但至少它会起作用。
每次将闪存驱动器插入USB端口时,Windows操作系统都会为其分配一个驱动器号。为了这次讨论的目的,我们把那封信叫做“F”。
这段代码查看我们是否可以cd到
f:\
。如果可以将cd插入f:\
,那么我们可以断定“F”已被分配为驱动器号,并且在假定您的闪存驱动器始终被分配为“F”的情况下,我们可以断定您的闪存驱动器已插入。相关问题 更多 >
编程相关推荐