How would I go about programmatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
我将如何以编程方式更改Mac OS X中的桌面背景?我想使用python,但我对任何可能的方式感兴趣。我可以连接终端并拨打某个命令吗?
9 个解决方案
#1
36
From python, if you have appscript installed (sudo easy_install appscript
), you can simply do
从python,如果你安装了appscript(sudo easy_install appscript),你就可以做到
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
Otherwise, this applescript will change the desktop background
否则,这个AppleScript将改变桌面背景
tell application "Finder"
set desktop picture to POSIX file "/your/filename.jpg"
end tell
You can run it from the command line using osascript
, or from Python using something like
您可以使用osascript从命令行运行它,或者使用类似的东西从Python运行它
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)
#2
21
If you are doing this for the current user, you can run, from a shell:
如果您正在为当前用户执行此操作,则可以从shell运行:
defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
Or, as root, for another user:
或者,作为root,为另一个用户:
/usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist
You will of course want to replace the image filename and user name.
您当然希望替换图像文件名和用户名。
The new setting will take effect when the Dock starts up -- either at login, or, when you
新设置将在Dock启动时生效 - 无论是在登录时,还是在您启动时
killall Dock
[Based on a posting elsewhere, and based on information from Matt Miller's answer.]
[基于其他地方的帖子,并根据Matt Miller的答案提供的信息。]
#3
12
I had this same question, except that I wanted to change the wallpaper on all attached monitors. Here's a Python script using appscript
(mentioned above; sudo easy_install appscript
) which does just that.
我有同样的问题,除了我想要更改所有连接的显示器上的壁纸。这是一个使用appscript的Python脚本(如上所述; sudo easy_install appscript)就是这样做的。
#!/usr/bin/python
from appscript import *
import argparse
def __main__():
parser = argparse.ArgumentParser(description='Set desktop wallpaper.')
parser.add_argument('file', type=file, help='File to use as wallpaper.')
args = parser.parse_args()
f = args.file
se = app('System Events')
desktops = se.desktops.display_name.get()
for d in desktops:
desk = se.desktops[its.display_name == d]
desk.picture.set(mactypes.File(f.name))
__main__()
#4
4
You can call "defaults write com.apple.Desktop Background ..." as described in this article: http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/
您可以按照本文所述调用“defaults write com.apple.Desktop Background ...”:http://tysthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-和的launchd /
The article also goes into scripting this to run automatically, but the first little bit should get you started.
本文还将脚本编写为自动运行,但第一点应该让你开始。
You might also be interested in the defaults man pages: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html
您可能还对默认手册页感兴趣:http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html
#5
3
The one-line solution for Mavericks is:
小牛队的一线解决方案是:
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/Library/Desktop Pictures/Earth Horizon.jpg"'
#6
2
Building on dF.'s answer, you could do it with Apple Script without Finder and you can do it for multiple desktops.
基于dF。的答案,您可以使用没有Finder的Apple Script来完成它,您可以为多个桌面执行此操作。
To set the wallpaper for desktop i
(desktop numbers start at 1):
要为桌面i设置壁纸(桌面编号从1开始):
tell application "System Events"
set currDesktop to item i of desktop
set currDesktop's picture to "image_path"
end tell
This is what I ended up doing (in Python):
这就是我最终做的(在Python中):
SET_DESKTOP_IMAGE_WRAPPER = """/usr/bin/osascript<<END
tell application "System Events"
{}
end tell
END"""
SET_DESKTOP_IMAGE = """
set currDesktop to item {idx} of desktops
set currDesktop's picture to "{image_path}"
"""
def set_wallpapers(images):
""" images is an array of file paths of desktops """
script_contents = ""
for i, img in enumerate(images):
idx = i+1
script_contents += SET_DESKTOP_IMAGE.format(idx=idx, image_path=img)
script = SET_DESKTOP_IMAGE_WRAPPER.format(script_contents)
subprocess.check_call(script, shell=True)
Sometimes, the desktop images don't appear immediately. I don't know why this happens, but restarting the dock fixes it. To do that from python:
有时,桌面图像不会立即显示。我不知道为什么会这样,但重新启动扩展坞会修复它。要从python执行此操作:
subprocess.check_call("killall Dock", shell=True)
By the way, you can get the number of desktops on the system using this AppleScript code:
顺便说一句,您可以使用此AppleScript代码获取系统上的桌面数量:
tell application "System Events"
get the number of desktops
end tell
you can use that with subprocess.check_output
to get the output
您可以使用subprocess.check_output来获取输出
#7
1
To add to Matt Miller's response: you can use subprocess.call() to execute a shell command as so:
要添加到Matt Miller的响应:您可以使用subprocess.call()执行shell命令,如下所示:
import subprocess
subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...])
#8
0
You could also use py-appscript instead of Popening osascript or use ScriptingBridge with pyobjc which is included in 10.5 but a bit more cumbersome to use.
您也可以使用py-appscript而不是Popening osascript或者将ScriptingBridge与pyobjc一起使用,pyobjc包含在10.5中,但使用起来有点麻烦。
#9
0
Another way to programmatically change the desktop wallpaper is to simply point the wallpaper setting at a file. Use your program to overwrite the file with the new design, then restart the dock: killall Dock
.
以编程方式更改桌面墙纸的另一种方法是简单地将壁纸设置指向文件。使用您的程序用新设计覆盖文件,然后重新启动dock:killall Dock。
The following depends on Xcode, lynx and wget, but here's how I automatically download and install a monthly wallpaper on Mountain Lion (shamelessly stolen and adapted from http://ubuntuforums.org/showthread.php?t=1409827) :
以下内容取决于Xcode,lynx和wget,但这里是我如何自动下载并安装Mountain Lion上的月度壁纸(无耻地被盗并改编自http://ubuntuforums.org/showthread.php?t=1409827):
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/local/bin
size=1440
dest="/usr/local/share/backgrounds/wallpaperEAA.jpg"
read -r baseurl < <(lynx -nonumbers -listonly -dump 'http://www.eaa.org/en/eaa/aviation-education-and-resources/airplane-desktop-wallpaper' | grep $size) &&
wget -q "$baseurl" -O "$dest"
killall Dock
Dump it into /etc/periodic/monthly/
and baby, you got a stew goin!
将它转储到/ etc / periodic / monthly /和宝贝,你有一个炖肉!
#1
36
From python, if you have appscript installed (sudo easy_install appscript
), you can simply do
从python,如果你安装了appscript(sudo easy_install appscript),你就可以做到
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
Otherwise, this applescript will change the desktop background
否则,这个AppleScript将改变桌面背景
tell application "Finder"
set desktop picture to POSIX file "/your/filename.jpg"
end tell
You can run it from the command line using osascript
, or from Python using something like
您可以使用osascript从命令行运行它,或者使用类似的东西从Python运行它
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)
#2
21
If you are doing this for the current user, you can run, from a shell:
如果您正在为当前用户执行此操作,则可以从shell运行:
defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
Or, as root, for another user:
或者,作为root,为另一个用户:
/usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist
You will of course want to replace the image filename and user name.
您当然希望替换图像文件名和用户名。
The new setting will take effect when the Dock starts up -- either at login, or, when you
新设置将在Dock启动时生效 - 无论是在登录时,还是在您启动时
killall Dock
[Based on a posting elsewhere, and based on information from Matt Miller's answer.]
[基于其他地方的帖子,并根据Matt Miller的答案提供的信息。]
#3
12
I had this same question, except that I wanted to change the wallpaper on all attached monitors. Here's a Python script using appscript
(mentioned above; sudo easy_install appscript
) which does just that.
我有同样的问题,除了我想要更改所有连接的显示器上的壁纸。这是一个使用appscript的Python脚本(如上所述; sudo easy_install appscript)就是这样做的。
#!/usr/bin/python
from appscript import *
import argparse
def __main__():
parser = argparse.ArgumentParser(description='Set desktop wallpaper.')
parser.add_argument('file', type=file, help='File to use as wallpaper.')
args = parser.parse_args()
f = args.file
se = app('System Events')
desktops = se.desktops.display_name.get()
for d in desktops:
desk = se.desktops[its.display_name == d]
desk.picture.set(mactypes.File(f.name))
__main__()
#4
4
You can call "defaults write com.apple.Desktop Background ..." as described in this article: http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/
您可以按照本文所述调用“defaults write com.apple.Desktop Background ...”:http://tysthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-和的launchd /
The article also goes into scripting this to run automatically, but the first little bit should get you started.
本文还将脚本编写为自动运行,但第一点应该让你开始。
You might also be interested in the defaults man pages: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html
您可能还对默认手册页感兴趣:http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html
#5
3
The one-line solution for Mavericks is:
小牛队的一线解决方案是:
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/Library/Desktop Pictures/Earth Horizon.jpg"'
#6
2
Building on dF.'s answer, you could do it with Apple Script without Finder and you can do it for multiple desktops.
基于dF。的答案,您可以使用没有Finder的Apple Script来完成它,您可以为多个桌面执行此操作。
To set the wallpaper for desktop i
(desktop numbers start at 1):
要为桌面i设置壁纸(桌面编号从1开始):
tell application "System Events"
set currDesktop to item i of desktop
set currDesktop's picture to "image_path"
end tell
This is what I ended up doing (in Python):
这就是我最终做的(在Python中):
SET_DESKTOP_IMAGE_WRAPPER = """/usr/bin/osascript<<END
tell application "System Events"
{}
end tell
END"""
SET_DESKTOP_IMAGE = """
set currDesktop to item {idx} of desktops
set currDesktop's picture to "{image_path}"
"""
def set_wallpapers(images):
""" images is an array of file paths of desktops """
script_contents = ""
for i, img in enumerate(images):
idx = i+1
script_contents += SET_DESKTOP_IMAGE.format(idx=idx, image_path=img)
script = SET_DESKTOP_IMAGE_WRAPPER.format(script_contents)
subprocess.check_call(script, shell=True)
Sometimes, the desktop images don't appear immediately. I don't know why this happens, but restarting the dock fixes it. To do that from python:
有时,桌面图像不会立即显示。我不知道为什么会这样,但重新启动扩展坞会修复它。要从python执行此操作:
subprocess.check_call("killall Dock", shell=True)
By the way, you can get the number of desktops on the system using this AppleScript code:
顺便说一句,您可以使用此AppleScript代码获取系统上的桌面数量:
tell application "System Events"
get the number of desktops
end tell
you can use that with subprocess.check_output
to get the output
您可以使用subprocess.check_output来获取输出
#7
1
To add to Matt Miller's response: you can use subprocess.call() to execute a shell command as so:
要添加到Matt Miller的响应:您可以使用subprocess.call()执行shell命令,如下所示:
import subprocess
subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...])
#8
0
You could also use py-appscript instead of Popening osascript or use ScriptingBridge with pyobjc which is included in 10.5 but a bit more cumbersome to use.
您也可以使用py-appscript而不是Popening osascript或者将ScriptingBridge与pyobjc一起使用,pyobjc包含在10.5中,但使用起来有点麻烦。
#9
0
Another way to programmatically change the desktop wallpaper is to simply point the wallpaper setting at a file. Use your program to overwrite the file with the new design, then restart the dock: killall Dock
.
以编程方式更改桌面墙纸的另一种方法是简单地将壁纸设置指向文件。使用您的程序用新设计覆盖文件,然后重新启动dock:killall Dock。
The following depends on Xcode, lynx and wget, but here's how I automatically download and install a monthly wallpaper on Mountain Lion (shamelessly stolen and adapted from http://ubuntuforums.org/showthread.php?t=1409827) :
以下内容取决于Xcode,lynx和wget,但这里是我如何自动下载并安装Mountain Lion上的月度壁纸(无耻地被盗并改编自http://ubuntuforums.org/showthread.php?t=1409827):
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/local/bin
size=1440
dest="/usr/local/share/backgrounds/wallpaperEAA.jpg"
read -r baseurl < <(lynx -nonumbers -listonly -dump 'http://www.eaa.org/en/eaa/aviation-education-and-resources/airplane-desktop-wallpaper' | grep $size) &&
wget -q "$baseurl" -O "$dest"
killall Dock
Dump it into /etc/periodic/monthly/
and baby, you got a stew goin!
将它转储到/ etc / periodic / monthly /和宝贝,你有一个炖肉!