Search code examples
python-3.xraspberry-piraspbiancd-rom

is there a way to check if the cd drive has a CD with python


I'm trying to make a program that checks when a cd is inserted with the specific name "PlayMe" and then have the program play the one track on it. The computer is a raspberry pi4 with raspbian.

I have tried just scanning for when the file tree appears, and it works once but when the disc is physically removed it still has the tree.I have also tried using pygame's cdrom method to get_empty and get_name. I don't know of a better way to do this.

import pygame

pygame.init()

print(pygame.cdrom.get_count())

pygame.cdrom.get_empty(0)

When it gets run I get the output from the cdrom.get_count as 1 but the get empty gives:

"AttributeError: module 'pygame.cdrom' has no attribute 'get_empty'"


Solution

  • I have no way to test this as my computer does not have a cd drive, but how about something like this? The idea is that you not only have to create a pygame CD object, but also call the pygame-specific init function for it before it is usable per the documentation.

    import pygame
    
    pygame.init()#should also automatically initialize the pygame cdrom module
    num_drives = pygame.cdrom.get_count()
    if num_drives == 0:
        raise ValueError("Computer does not have a CD-drive")
    drive = pygame.cdrom.CD(0)#first drive, probably default?
    drive.init()
    if not drive.get_empty():
        print("A CD is in this drive")
    else:
        print("No CD is in this drive")
    drive.quit()