Be notified when disc in CD drive

I would like for my program to do something when a CD is put in the CD drive. The method I devised is this:

def start_cddrive_watcher(self):
    CDROM_DRIVE = '/dev/cdrom'
    fd =, os.O_RDONLY | os.O_NONBLOCK)
    # 0x5326 = CDROM_DRIVE_STATUS (see linux/cdrom.h).
    # Status values:
    #   1 = no disc
    #   2 = tray open
    #   3 = drive getting ready
    #   4 = disc ready
    def poll_status():
        status = fcntl.ioctl(fd, 0x5326)
        return True
    GLib.timeout_add_seconds(1, poll_status)

This code works, but I am wondering whether there is a better way to solve the problem using something like GLib.io_add_watch. Would it be more efficient to somehow have the OS signal when there is a change in status rather than have GLib constantly poll, or is GLib’s polling is so efficient that any other solution would be gratuitous optimization?

1 Like

Can Gio and it’s signals help in the stuff here ? (I don’t know the exact function or object, but Gio has the ability to monitor file changes etc.) :sweat_smile:

I found that Gio.Device has a method called poll_for_media, which sounds like what I need. However, I have not found good documentation on how to use Gio.Device. Moreover, if poll_for_media is polling, then it isn’t obvious that it offers any advantage over my solution, which also does polling. I probably won’t pursue this option, but I am glad to know that it exists, so thanks for your suggestion.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.