繁体   English   中英

Python / Windows:仅列出 USB 可移动驱动器

[英]Python / Windows: List only USB removable drives

是否可以使用 Python 在 Windows 上仅获取可移动 USB 驱动器和(不是必需的)它们的标签? 在 Linux (Ubuntu) 上,您只需要列出/media文件夹。

这是我当前的代码(它列出了所有可用的驱动器号,包括系统驱动器、CD/DVD 驱动器等):

import win32api

dv = win32api.GetLogicalDriveStrings()
dv = dv.split('\000')[:-1]
print dv

结果是这样的: ['C:\\\\', 'D:\\\\', 'E:\\\\']

我只想要 USB 大容量存储驱动器...有什么帮助吗?

问候...

import win32file

def rdrive(d):
    # returns boolean, true if drive d is removable
    return win32file.GetDriveType(d)==win32file.DRIVE_REMOVABLE

您还可以使用 ctypes 模块来获取可移动驱动器列表。

from ctypes import windll    
def get_drives():
        drives = []
        bitmask = windll.kernel32.GetLogicalDrives()
        for letter in map(chr, range(65, 91)):
            if bitmask & 1:
                drives.append(letter)
            bitmask >>= 1
        return drives

您可以使用相同的列表并将其与新的驱动器列表进行比较以添加可移动驱动器。

    drives_list=get_drives()
    drives_list1=[]
    while True:
      drives_list1=get_drives()
      if len(list(set(drives_list1) - set(drives_list))) > 0:
            print("Drives Added"+str(set(drives_list1) - set(drives_list)))

有关更多信息,请参阅 github 上的此 repo drivemonitoring

我自己也有类似的问题。 使用@user2532756 的回答中的逻辑,我为这个问题的任何新访问者组合了这个快速功能:

基本上,只需调用该函数,它就会将所有可移动驱动器list返回给调用者。

import win32api
import win32con
import win32file

def get_removable_drives():
    drives = [i for i in win32api.GetLogicalDriveStrings().split('\x00') if i]
    rdrives = [d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE]
    return rdrives

例如:调用get_removable_drives()将输出:

['E:\\']

psutil库比win32api好得多。 它提供了大量有关驱动器的信息,并且格式很好。 https://github.com/giampaolo/psutil

import psutils as p
externals = [i.mountpoint for i in p.disk_partitions() if 'removable' in i.opts]

我也在寻找这个,但后来使用wmi模块“从头开始”。

import wmi

LOCAL_MACHINE_CONNECTION = wmi.WMI()

# .Win32_LogicalDisk() returns a list of wmi_object objects. Each of them represents a storage device connected to the local machine (serial number, path, description, e.t.c)
drives_available = [wmi_object.deviceID for wmi_object in LOCAL_MACHINE_CONNECTION.Win32_LogicalDisk() if wmi_object.description == "Removable Disk"]

# .deviceID is the tag (or letter like F:, G:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM