Search code examples
pythonapplescript

Python won't change wallpaper on Mac OS


I found some code that should change my wallpaper:

import subprocess

SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""

def set_desktop_background(filename):
    subprocess.Popen(SCRIPT%filename, shell=True)

set_desktop_background("image.png")

But I get this error:

30:45: execution error: Finder got an error: AppleEvent handler failed. (-10000)

Does anyone know what went wrong, or what I can do about this?


Solution

  • Your AppleScript is causing the error. Instead, try using the code from this answer. Note that you need to use an absolute path, so you should use os.path.abspath():

    import subprocess
    import os
    
    SCRIPT = """/usr/bin/osascript<<END
    tell application "System Events" to set picture of (reference to current desktop) to "%s"
    END"""
    
    
    def set_desktop_background(filename):
        abspath = os.path.abspath(filename)
        subprocess.Popen(SCRIPT % abspath, shell=True)
    
    
    set_desktop_background("image.png")