Skip to content

Instantly share code, notes, and snippets.

@chrisduran
Created August 21, 2019 08:25
Show Gist options
  • Save chrisduran/a1ad3684d12bc9aa7b2486a1ed2458fc to your computer and use it in GitHub Desktop.
Save chrisduran/a1ad3684d12bc9aa7b2486a1ed2458fc to your computer and use it in GitHub Desktop.
Eject/Close CD Drive in Windows (Python)

For Python 3.7.x:

Assumes you only have a single optical drive, only tested under Windows 10. Exploits the quirk that the C callback takes a much shorter period of time to return if the drive is already open, then it does when opening (presumably waits until the drive reports a successful opening somehow). It assumes that if the time passed after an opening command is below a certain value (1.0), then the drive is already open and needs closing.

You may need to change the float value on line 5 if your drive opens super quick. (I was getting values between 0.1-0.3 when already open, and 2.0+ when closed).

Create Binary

  1. Install Python 3.7.x (https://www.python.org/downloads/)
  2. Install pyinstaller (pip install pyinstaller)
  3. Create EXE (pyinstaller -wF eject.py) //-w for no console, -F for a self-contained EXE
  4. Use EXE to open and close CD-DRIVE (bind to a key, run from console, go nuts!)
import ctypes
import time
start = time.perf_counter()
ctypes.windll.winmm.mciSendStringW("set cdaudio door open", None, 0, None)
if (time.perf_counter()-start) < 1.0:
ctypes.windll.winmm.mciSendStringW("set cdaudio door closed", None, 0, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment