pythonpython-3.xmacosscreensaver

Turn Screensaver off on macOS Monterey via Python


I have a Python media player that I want to turn off the screensaver while the video is playing. This works great on Windows, but I can't get it to work on the Mac. The top code with the caffeine module works in PyCharm. Unfortunately, when the program is compiled it crashes at this point. Unfortunately the other code snippets don't work, or am I making an obvious mistake?

def turn_screen_saver_off():
    if sys.platform == "win32":
        print("turn_screen_saver_off")
        ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
    elif sys.platform == "darwin":
        print("turn_screen_saver_off")
        #import caffeine
        #caffeine.on(display=True)
        
        #subprocess.run(['caffeinate', '-s']) # Keep the system awake
        
        #from AppKit import NSBundle
        #bundle = NSBundle.mainBundle()
        #info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        #info['NSScreensaverDisabled'] = True
        
        #script = 'tell application "System Events" to set sleep to 0'
        #os.system(f"osascript -e '{script}'")


def turn_screen_saver_on():
    if sys.platform == "win32":
        print("turn_screen_saver_on")
        ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
    elif sys.platform == "darwin":
        print("turn_screen_saver_on")
        #import caffeine
        #caffeine.off()
        
        #subprocess.run(['killall', 'caffeinate']) # Allow the system to sleep
        
        ##from AppKit import NSBundle
        #bundle = NSBundle.mainBundle()
        #info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        #info['NSScreensaverDisabled'] = True
        
        #script = 'tell application "System Events" to set sleep to 1'
        #os.system(f"osascript -e '{script}'")

I tried following code. But it doesn't work.

        #import caffeine
        #caffeine.on(display=True)
        
        #subprocess.run(['caffeinate', '-s']) # Keep the system awake
        
        #from AppKit import NSBundle
        #bundle = NSBundle.mainBundle()
        #info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        #info['NSScreensaverDisabled'] = True
        
        #script = 'tell application "System Events" to set sleep to 0'
        #os.system(f"osascript -e '{script}'")

Solution

  • Try saving the screen saver time with this commmand:

     defaults -currentHost read com.apple.screensaver idleTime
    

    Then try modifying the screen saver default directly with this command:

    defaults -currentHost write com.apple.screensaver idleTime 0
    

    Found this solution on this blog check it out if you'd like!