简体   繁体   English

如何使用 Python 列出外部驱动器? (外置 USB 硬盘,外置 USB flash 驱动器)

[英]How to list external drives with Python? (external USB HDD, external USB flash drive)

I have read Is there a way to list all the available Windows' drives?我已阅读有没有办法列出所有可用的 Windows 驱动器? and Cross platform way to list disk drives on Linux, Windows and Mac using Python?跨平台方式列出 Linux、Windows 和 Mac 上的磁盘驱动器使用 Python? and methods like:和方法如:

import win32api
print(win32api.GetLogicalDriveStrings().split('\000'))

but how to limit this list to external USB storage devices only?但是如何将此列表限制为仅限外部 USB 存储设备? (USB HDD, USB SSD, USB flash drive, etc.) (USB硬盘、USB SSD、USB flash驱动等)

PS: is it possible with very few dependencies? PS:依赖很少吗? (maybe just ctypes or win32api ) (也许只是ctypeswin32api

wmi will do the task wmi python wmi 将执行wmi python任务

import wmi

get = wmi.WMI()

drives_available = [wmi_object.deviceID for wmi_object in get.Win32_LogicalDisk() if wmi_object.description == "Removable Disk"]
print(drives_available)

Output Output

['E:']

using psutil使用psutil

import psutil as ps
ext_drives = [i.mountpoint for i in ps.disk_partitions() if 'removable' in i.opts]
print(ext_drives)

Output Output

['E:']

uisng win32 api win32 api

import win32api
import win32con
import win32file

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



get()

Output Output

['E:']

If you check out https://devblogs.microsoft.com/scripting/inventory-drive-types-by-using-powershell/ and use power shell WMI commands, you can list all types of devices according to its id如果您查看https://devblogs.microsoft.com/scripting/inventory-drive-types-by-using-powershell/并使用 power shell WMI 命令,您可以根据其 id 列出所有类型的设备

import subprocess
import json


def list_drives():
    """
    Get a list of drives using WMI
    :return: list of drives
    """
    proc = subprocess.run(
        args=[
            'powershell',
            '-noprofile',
            '-command',
            'Get-WmiObject -Class Win32_LogicalDisk | Select-Object deviceid,volumename,drivetype | ConvertTo-Json'
        ],
        text=True,
        stdout=subprocess.PIPE
    )
    devices = json.loads(proc.stdout)
    for device in devices:
        if device['drivetype'] == 2:  # change to get drives with other types
            print(f'{device["deviceid"]}: {device["volumename"]}')


list_drives()

Here is a solution with only ctypes and no third-party module to pip install , inspired by Bhargav's solution:这是一个只有ctypes而没有第三方模块到pip install的解决方案,灵感来自 Bhargav 的解决方案:

import ctypes, string
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
drives = [letter for i, letter in enumerate(string.ascii_uppercase) if bitmask & (1 << i)]
ext_drives = [letter for letter in drives if ctypes.windll.kernel32.GetDriveTypeW(letter + ':') == 2]  # DRIVE_REMOVABLE = 2
print(ext_drives)

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

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