简体   繁体   English

Python:获取USB闪存驱动器设备的名称[windows]

[英]Python: get name of a USB flash drive device [windows]

I'm trying to write little program which will be able to read some informations about REMOVEABLE_DEVICE (USB). 我正在尝试编写一些小程序,该程序将能够读取有关REMOVEABLE_DEVICE(USB)的一些信息。 I've tried pyusb but I was not able to pull data I need. 我尝试了pyusb,但无法提取所需的数据。

I would like to read from the system the name of the USB device. 我想从系统中读取USB设备的名称。

In this format: 以这种格式:

USB Flash Memory - this is the model information
Removable Disk (H:) - this is the name of device

Generic Flash Disk
USB DISK (F:)

Lexar USB Flash Drive
Lexar (I:)

I am able to get the model information with win32com.client library, inspired from here , but I am not able to get name of the device shown in Windows explorer. 我可以从这里得到启发,使用win32com.client库获取模型信息,但无法获取Windows资源管理器中显示的设备名称。

Maybe I am using wrong library? 也许我使用了错误的库?

Here is my code: 这是我的代码:

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\"")
for objItem in colItems:
    if objItem.Caption != None:
        print "Caption:" + ` objItem.Caption[:-11]`

Here is link for Windows Win32_DiskDrive Class: link 这是Windows Win32_DiskDrive类的链接链接

Thank you in advance for your help. 预先感谢您的帮助。

I will look odd but it will work (get list of all removable volume's Label's ) 我看起来很奇怪,但是可以正常工作(获取所有可移动卷的Label's列表)

import os
os.system('echo list volume > Ravi.txt')
path1 = os.path.join(os.getcwd(),"Ravi.txt")
os.system('diskpart /s '+path1+' > logfile.txt')
path2 = os.path.join(os.getcwd(),"logfile.txt")

Str = open(path2).read()
Str = Str.split('\n')
matching = [s for s in Str if "Removable" in s]

for i in matching:
    i = ' '.join(i.split())
    i = i.split(" ")
    print i[3]+"("+i[2]+":)"

output 产量

MYPENDRIVE(D:)

Disclaimer : I haven't really got any experience with the win32com.client library. 免责声明 :我实际上对win32com.client库没有任何经验。

By starting with Win32_DiskDrive like you did, I went over Win32_DiskDriveToDiskPartition and Win32_LogicalDiskToPartition , and then to Win32_LogicalDisk to get the VolumeName which seems what you want. 通过像您一样从Win32_DiskDrive开始,我遍历了Win32_DiskDriveToDiskPartitionWin32_LogicalDiskToPartition ,然后转到Win32_LogicalDisk以获取看起来像您想要的VolumeName

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")

# 1. Win32_DiskDrive
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\"")
DiskDrive_DeviceID = colItems[0].DeviceID.replace('\\', '').replace('.', '')
DiskDrive_Caption = colItems[0].Caption

print 'DiskDrive DeviceID:', DiskDrive_DeviceID

# 2. Win32_DiskDriveToDiskPartition
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_DiskDriveToDiskPartition")
for objItem in colItems:
    if DiskDrive_DeviceID in str(objItem.Antecedent):
        DiskPartition_DeviceID = objItem.Dependent.split('=')[1].replace('"', '')

print 'DiskPartition DeviceID:', DiskPartition_DeviceID

# 3. Win32_LogicalDiskToPartition
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_LogicalDiskToPartition")
for objItem in colItems:
    if DiskPartition_DeviceID in str(objItem.Antecedent):
        LogicalDisk_DeviceID = objItem.Dependent.split('=')[1].replace('"', '')

print 'LogicalDisk DeviceID:', LogicalDisk_DeviceID

# 4. Win32_LogicalDisk
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_LogicalDisk WHERE DeviceID=\"" + LogicalDisk_DeviceID + "\"")
print 'LogicalDisk VolumeName:', colItems[0].VolumeName
print

# putting it together
print DiskDrive_Caption
print colItems[0].VolumeName, '(' + LogicalDisk_DeviceID + ')'

Works for me: 为我工作:

DiskDrive DeviceID: PHYSICALDRIVE1
DiskPartition DeviceID: Disk #1, Partition #0
LogicalDisk DeviceID: D:
LogicalDisk VolumeName: PENDRIVE

Sony Storage Media USB Device
PENDRIVE (D:)

This seems to provide a complicated, but possible way, maybe you can simplify it even more. 这似乎提供了一种复杂但可行的方法,也许您可​​以进一步简化它。 My only simplification is leaving out Win32_DiskPartition already because we only need the connection. 我唯一的简化就是已经省略了Win32_DiskPartition因为我们只需要连接。

Please note: 请注意:

  • I'm not sure what's the "clean" way to unpack something like \\\\.\\PHYSICALDRIVE1 , but it should be possible to get rid of the .replace() -methods. 我不确定解压\\\\.\\PHYSICALDRIVE1之类的“干净”方法是什么,但是应该可以摆脱.replace()方法。
  • I'm not sure if it's possible to integrate the loops in steps 2 and 3 into the query? 我不确定是否可以将步骤2和3中的循环集成到查询中? That would also simplify it a lot (maybe it's possible to JOIN them SQL-like?). 这也将大大简化它(也许可以像SQL那样JOIN它们?)。
  • (The code above will only work for a single USB drive.) (以上代码仅适用于单个USB驱动器。)

I used the approach of @adrianus and improved a bit on it to return multiple usb drives. 我使用了@adrianus的方法,并对其进行了一些改进以返回多个USB驱动器。 For how it works check his answer. 对于如何工作,请检查他的答案。 For quick and dirty code that hopefully works for you check below :) 对于希望对您有用的快速而肮脏的代码,请查看以下内容:)

def get_usb_volume_name():  # pragma: no cover
    str_computer = "."
    logical_disk_device_ids = []
    volumes = []
    try:
        obj_wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        obj_swbem_services = obj_wmi_service.ConnectServer(str_computer, "root\cimv2")

    # 1. Win32_DiskDrive
    col_items = obj_swbem_services.ExecQuery("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\"")
    for item in col_items:
        disk_drive_device_ids = item.DeviceID.replace('\\', '').replace('.', '')

    # 2. Win32_DiskDriveToDiskPartition
    col_items = obj_swbem_services.ExecQuery("SELECT * from Win32_DiskDriveToDiskPartition")
    disk_partition_device_ids = []
    for obj_item in col_items:
        for disk_drive_device_id in disk_drive_device_ids:
            if disk_drive_device_id in str(obj_item.Antecedent):
                disk_partition_device_ids.append(obj_item.Dependent.split('=')[1].replace('"', ''))
                break

    # 3. Win32_LogicalDiskToPartition
    col_items = obj_swbem_services.ExecQuery("SELECT * from Win32_LogicalDiskToPartition")
    for objItem in col_items:
        for disk_partition_device_id in disk_partition_device_ids:

            if disk_partition_device_id in str(objItem.Antecedent):
                logical_disk_device_ids.append(objItem.Dependent.split('=')[1].replace('"', ''))
                break

    # 4. Win32_LogicalDisk
    col_items = []
    for logical_disk_device_id in logical_disk_device_ids:
        col_items.append(obj_swbem_services.ExecQuery("SELECT * from Win32_LogicalDisk WHERE DeviceID=\"" +
                                                      logical_disk_device_id + "\""))

    for col_item in col_items:
        volumes.append(col_item[0].VolumeName)
except IndexError:
    pass
volumes_result = []
logical_disk_device_ids_result = []
for i in range(len(volumes)):
    if volumes[i] != "":
        volumes_result.append(volumes[i])
        logical_disk_device_ids_result.append(logical_disk_device_ids[i])

return logical_disk_device_ids_result, volumes_result

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

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