[python-win32] Eject a CD with win32file?

Joel Lawhead jlawhead@bellsouth.net
Sat, 23 Nov 2002 16:23:40 -0600

I'm trying to programatically eject a cd on a Win2k machine in Python. 
I found a simple working example in C with source and an executable at:

Based on that program and some research on MSDN it appears the steps for
ejecting a CD-ROM are to first get a file handle for the device using
win32file.CreateFile and then call win32file.DeviceIoControl() with the

I tried:

import win32file
from win32con import *

# Get a file handle for the CD-ROM device
hdevice = win32file.CreateFile('\\\\.\\G:', 0, 0,None,OPEN_EXISTING,0,0)

# Eject the cd
win32file.DeviceIoControl(hdevice,2,"", 0, None)

The win32file.CreateFile() returns without error. But the
win32file.DeviceIoControl() call returns:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
pywintypes.api_error: (1, 'DeviceIoControl', 'Incorrect function.')

The second parameter in DeviceIoControl is an integer but I don't know
what it is and have been guessing with several numbers to no avail. All
the documentation simply refers to the constant
"IOCTL_STORAGE_EJECT_MEDIA" and not an integer. So I'm not sure if that
call is my problem or if it's something else.

To get the job done of course I could always make an os.system() call to
the command line "eject.exe" program I mentioned above, but I feel like
I'm pretty close to doing it with Python and the win32 extenstions. 

I don't have a lot of experience working with windows mfc calls so any
help would be appreciated.