对于将来可能遇到此问题的任何人(以及我自己将来在此问题上的参考),此答案将 Thaer A 在此线程和 Felix Heide here 上的答案中的详细信息汇编成更全面的查找方式基于其卷名的驱动器。
因此,假设您有一个名称为 Backup Drive 的驱动器,您不知道它的字母,或者该驱动器是否已连接。您将执行以下操作:
首先,为了检查驱动器是否已连接,我们将创建一个所有已连接驱动器名称的列表,以便稍后检查是否有任何匹配 Backup Drive 以及所有驱动器号的列表以供以后使用。还值得注意的是,在这个过程的大部分时间里使用strip 和lower 可能不是一个坏主意,但我不会在这里打扰(至少现在是这样)。所以我们得到:
looking_for = "Backup Drive"
drive_names = []
drive_letters = []
接下来,让我们设置我们的WMI 对象以供以后使用:
import wmi
c = wmi.WMI()
现在我们遍历所有连接的驱动器并填写我们的两个列表:
for drive in c.Win32_LogicalDisk ():
drive_names.append(str(drive.VolumeName))
drive_letters.append(str(drive.Caption))
我们也可以在这里使用win32api 模块通过检查是否进行反向验证
win32api.GetVolumeInformation(str(drive.Caption) + "\\")[0]
等于drive.VolumeName。
然后我们可以检查驱动器是否连接,如果是则打印驱动器号:
if looking_for not in drive_names:
print("The drive is not connected currently.")
else:
print("The drive letter is " + str(drive_letters[drive_names.index(looking_for)]))
所以总的来说,还非常随意地添加了strip 和lower,我们得到:
import wmi
import win32api, pywintypes # optional
looking_for = "Backup Drive"
drive_names = []
drive_letters = []
c = wmi.WMI()
for drive in c.Win32_LogicalDisk ():
drive_names.append(str(drive.VolumeName).strip().lower())
drive_letters.append(str(drive.Caption).strip().lower())
# below is optional
# need a try catch because some drives might be empty but still show up (like D: drive with no disk inserted)
try:
if str(win32api.GetVolumeInformation(str(drive.Caption) + "\\")[0]).strip().lower() != str(drive.VolumeName).strip().lower():
print("Something has gone horribly wrong...")
except pywintypes.error:
pass
if looking_for.strip().lower() not in drive_names:
print("The drive is not connected currently.")
else:
print("The drive letter is " + str(drive_letters[drive_names.index(looking_for.strip().lower())]).upper())