python - 如何使用 Python 在 Windows 中检测闪存驱动器插件?

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

关于python - 如何使用 Python 在 Windows 中检测闪存驱动器插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1968539/

相关文章:

python - 将 100 个带标题的 CSV 文件合并为一个文件的最快方法是什么?

c++ - 间歇性地没有数据通过 boost::asio/io 完成端口传递

windows - 如何解决 bash 编码问题?

python - OpenCmis 客户端 - 创建露天标签

python - Pyinstaller 未被识别为内部或外部命令

Python3 相对导入在包中失败

c# - 如何获取之前连接的 USB 设备的时间戳?

java - 在 `javac.exe` 中找不到 `jdk\bin`

windows-7 - 如何编程引导加载程序..?想要一个装有 Windows 7、XP、Vista 和 98 SE 的 USB 闪存驱动器用于安装

python - 我需要能够通过 USB 运行 pycharm + 模块