【问题标题】:Python / Windows: List only USB removable drivesPython / Windows:仅列出 USB 可移动驱动器
【发布时间】:2012-09-04 14:58:51
【问题描述】:

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

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

import win32api

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

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

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

问候...

【问题讨论】:

标签: python windows pywin32 drive


【解决方案1】:
import win32file

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

【讨论】:

  • No module named 'win32file'
  • pip install pywin32
【解决方案2】:

我自己也有类似的问题。使用@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:\\']

【讨论】:

    【解决方案3】:

    您还可以使用 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。

    【讨论】:

      【解决方案4】:

      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]
      

      【讨论】:

        【解决方案5】:

        我也在寻找这个,但后来使用 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:)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-10
          • 2011-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-20
          • 1970-01-01
          相关资源
          最近更新 更多