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

发布于 2024-08-16 00:29:54 字数 197 浏览 6 评论 0原文

我想让我的 Windows 计算机在检测到已插入具有特定名称(例如“我的驱动器”)的闪存驱动器时运行 Python 脚本。

我怎样才能实现这一点?

我应该在 Windows 中使用某些工具还是有办法编写另一个 Python 脚本来在插入闪存驱动器后立即检测它是否存在? (如果脚本在计算机上,我会更喜欢它。)

(我是编程新手..)

I want to make my Windows computer run a Python script when it detects that a flash drive which has a particular name (for example "My drive") has been plugged in.

How can I achieve this?

Should I use some tool in Windows or is there a way to write another Python script to detect the presence of a flash drive as soon as it is plugged in? (I'd prefer it if the script was on the computer.)

(I'm a programming newbie.. )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

抱猫软卧 2024-08-23 00:29:54

基于“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."

Building on the "CD" approach, what if your script enumerated the list of drives, waited a few seconds for Windows to assign the drive letter, then re-enumerated the list? A python set could tell you what changed, no? The following worked for me:

# 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."
聚集的泪 2024-08-23 00:29:54

虽然您可以使用“inpectorG4dget”建议的类似方法,但这会非常低效。

为此,您需要使用 Win API。此页面可能对您有用:链接

要在 python 中使用 Win API,请查看此链接:链接

Though you can use a similar method as 'inpectorG4dget' suggested but that will be a lot inefficient.

You need to use Win API for this. This page might be of use to you: Link

And to use Win API's in python check this link out: Link

十二 2024-08-23 00:29:54

好吧,如果您使用的是 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

Well, if you're on a Linux distribution, then this question on SO would have the answer.

I can think of a round-about (not elegant) solution for your problem, but at the very least it would WORK.

Every time you insert your flash drive into a USB port, the Windows OS assigns a drive letter to it. For the purposes of this discussion, let's call that letter 'F'.

This code looks to see if we can cd into f:\. If it is possible to cd into f:\, then we can conclude that 'F' has been allocated as a drive letter, and under the assumption that your flash drive always gets assigned to 'F', we can conclude that your flash drive has been plugged in.

import os
def isPluggedIn(driveLetter):
    if os.system("cd " +driveLetter +":") == 0: return True
    else: return False
清音悠歌 2024-08-23 00:29:54
import subprocess

out = subprocess.check_output('wmic logicaldisk get  DriveType, caption', shell=True)

for drive in str(out).strip().split('\\r\\r\\n'):
    if '2' in drive:
        drive_litter = drive.split(':')[0]
        drive_type = drive.split(':')[1].strip()
        #print(drive_litter, drive_type)
        if drive_type == '2':
            print('Removable disk detected')
import subprocess

out = subprocess.check_output('wmic logicaldisk get  DriveType, caption', shell=True)

for drive in str(out).strip().split('\\r\\r\\n'):
    if '2' in drive:
        drive_litter = drive.split(':')[0]
        drive_type = drive.split(':')[1].strip()
        #print(drive_litter, drive_type)
        if drive_type == '2':
            print('Removable disk detected')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文