Mah*_*ghe 6 python windows usb-drive
我想让我的Windows计算机在检测到插入了具有特定名称的闪存驱动器(例如"我的驱动器")时运行Python脚本.
我怎样才能做到这一点?
我应该在Windows中使用某种工具还是有办法编写另一个Python脚本,以便在插入闪存驱动器后立即检测到它?(如果脚本在计算机上,我更喜欢它.)
(我是一个编程新手..)
建立在“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."
Run Code Online (Sandbox Code Playgroud)
好吧,如果你使用的是 Linux 发行版,那么SO 上的这个问题就会有答案。
我可以为你的问题想出一个迂回(不优雅)的解决方案,但至少它会起作用。
每次将闪存驱动器插入 USB 端口时,Windows 操作系统都会为其分配一个驱动器号。为了讨论的目的,我们将该字母称为“F”。
此代码查看我们是否可以 cd 进入f:\. 如果可以 cd 到f:\,那么我们可以得出结论,“F”已被分配为驱动器号,并且假设您的闪存驱动器始终分配给“F”,我们可以得出结论,您的闪存驱动器已被插入在。
import os
def isPluggedIn(driveLetter):
if os.system("cd " +driveLetter +":") == 0: return True
else: return False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9621 次 |
| 最近记录: |