Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate CD-Drives using Python (Windows)

Tags:

python

windows

How can I find out the drive letters of available CD/DVD drives?

I am using Python 2.5.4 on Windows.

like image 987
John Avatar asked Jul 12 '26 21:07

John


2 Answers

Using win32api you can get list of drives and using GetDriveType you can check what type of drive it is, you can access win32api either by 'Python for Windows Extensions' or ctypes module

Here is an example using 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

This outputs:

Drive: C
Type: DRIVE_FIXED
Drive: D
Type: DRIVE_FIXED
Drive: E
Type: DRIVE_CDROM
like image 126
Anurag Uniyal Avatar answered Jul 14 '26 11:07

Anurag Uniyal


If you use the WMI Module, it's very easy:

import wmi
c = wmi.WMI()
for cdrom in c.Win32_CDROMDrive():
    print cdrom.Drive, cdrom.MediaLoaded

The Drive attribute will give you the drive letter and MediaLoaded will tell you if there's something in the drive.

In case you didn't know, WMI standards for Windows Management Instrumentation and is an API that allows you to query management information about a system. (For what it's worth, WMI is the Windows implementation of the Common Information Model standard.) The Python WMI Module gives you easy access to the Windows WMI calls.

In the code above we query the Win32_CDROMDrive WMI Class to find out about the CD ROM drives on the system. This gives us a list of objects with a huge number of attributes which tells us everything we could ever want to know about the CD Drives. We check the drive letter and media state, since that's all we care about right now.

like image 41
Dave Webb Avatar answered Jul 14 '26 12:07

Dave Webb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!