秘密の本棚

気になることをなんでも書きます

ハロウィーンなのでMacの背景をスクリプトから変更する

今日はハロウィーンですね。Bingの背景がこれになってました。

f:id:nexusuica:20181031190611j:plain

以前WindowsAndroidの背景をBingの画像に設定するアプリを紹介したのですが、Macのアプリは有料でした。
nexusuica.hatenablog.jp
今回はBingの背景画像を取り込んで背景に設定するプログラムを自前で書いてみました。

流行りのPythonで実装

Bingの背景画像は以下のURLからjson形式でフェッチできます。

http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1

f:id:nexusuica:20181031193619p:plain

このjsonから画像のURL部分を取り出し、ファイルをローカルにダウンロードしたのち、AppleScriptMacのデスクトップの背景に設定します。実装はなんでもよかったのですがPythonでやってみました。

import json
import urllib.request
import subprocess
from os.path import join, expanduser

#ディレクトリを指定
dir = join(expanduser("~"), 'Documents/bing-wallpaper')

#画像をフェッチ
url = "http://www.bing.com/HPImageArchive.aspx?format=js&n=1"
response = urllib.request.urlopen(url)
content = json.loads(response.read().decode('utf8'))
print(content['images'][0]['url'])
image_url = "http://www.bing.com"+content['images'][0]['url']
date = content['images'][0]['fullstartdate']
print(image_url)
filename = date+".jpg"
filepath = join(dir, filename)
urllib.request.urlretrieve(image_url,"{0}".format(filepath))

#背景に設定
script = """/usr/bin/osascript<<END
tell application "System Events"
set picture of every desktop to POSIX file "%s"
end tell
END"""
subprocess.Popen(script%filepath,shell=True)

あとはこのスクリプトを定期的に実行させてやれば毎日画像が変わります。cronを設定してもよいのですが面倒だったのでBetterTouchToolでスリープ解除後に実行させるように設定しました。
nexusuica.hatenablog.jp

これで毎日背景に飽きません。Bingの画像は季節感もありますしクオリティが高いので良いですね。ハッピーハロウィーン

f:id:nexusuica:20181031192908j:plain