6

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

我怎样才能做到这一点?

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

(我是一个编程新手..)

4

4 回答 4

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."
于 2012-03-06T05:36:43.290 回答
4

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

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

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

于 2009-12-28T13:43:48.993 回答
3

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
于 2009-12-28T09:50:42.567 回答
0
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')
于 2022-02-14T18:04:00.117 回答