使用Python枚举CD驱动器(Windows)

Joh*_*ohn 2 python windows

如何找到可用CD/DVD驱动器的驱动器号?

我在Windows上使用Python 2.5.4.

Anu*_*yal 9

使用win32api你可以获得驱动器列表并使用GetDriveType 你可以检查它是什么类型的驱动器,你可以通过'Python for Windows Extensions'或ctypes模块访问win32api

以下是使用ctypes的示例:

import string
from ctypes import windll

driveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK']

def get_drives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1

    return drives

for drive in get_drives():
    if not drive: continue
    print "Drive:", drive
    try:
        typeIndex = windll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
        print "Type:",driveTypes[typeIndex]
    except Exception,e:
        print "error:",e
Run Code Online (Sandbox Code Playgroud)

这输出:

Drive: C
Type: DRIVE_FIXED
Drive: D
Type: DRIVE_FIXED
Drive: E
Type: DRIVE_CDROM
Run Code Online (Sandbox Code Playgroud)