Mac 每天自动更换为 Bing.com 壁纸

发布于 2018-03-21 21:27:37

原理

  1. 只要电脑开启,一定时间间隔尝试下载今天 www.bing.com 的壁纸
  2. 一定时间间隔归档往日的壁纸到别的文件夹
  3. Mac 设置为定时更换壁纸

定时任务用 Linux 的 crontab 来实现

1.定时下载壁纸

这里用 Go 语言写了一个简单的程序,源码仓库地址:https://github.com/weaming/bingwptoday

go get github.com/weaming/bingwptoday
$ bingwptoday -h
Usage of bingwptoday:
  -d string
        Directory to store wallpapers. (default "/Users/garden/Downloads/BingWallpapers")
  -n string
        Number of wallpapers to download. (default "1")
  -t	Whether add timestamp in picture name.

使用的API接口是:http://www.bing.com/HPImageArchive.aspx?format=js&n=1

format: js 返回 JSON 格式数据
n: 返回壁纸的张数

定义 JSON 解析用的结构体:

type API struct {
    Images []struct {
            CopyRight     string `json:"copyright"`
            CopyRightLink string `json:"copyrightlink"`
            Url           string `json:"url"`
            UrlBase       string `json:"urlbase"`
        } `json:"images"`
}

json库的Unmarshal()方法来解析 JSON 字符串。

已经存在的壁纸,不会重复下载。

2. 定时归档壁纸

17-02-20更新:通过命令行更新壁纸

这种任务就写个简单的 Python 脚本好了,除了最新的壁纸,其他壁纸统统移到另外一个文件夹

#!/usr/bin/env python3
# coding: utf-8
"""
Author       : weaming
Created Time : 2017-02-08 23:00:58

File Name    : MacWallpaper.py
Prerequisities:
    go get -u github.com/weaming/bingwptoday
Description  :
    Download Bing.com today wallpaper and set it as computer desktop wallpaper.
"""
import os
import subprocess
from filetree import File

root = os.path.expanduser("~/Downloads/BingWallpapers")
to = "archived"


def run_shell(commands):
    return subprocess.run(commands).returncode == 0


def download():
    return run_shell([os.path.expanduser("~/go/bin/bingwptoday"), "-t"])


def archive_and_set_wp():
    F = File(root)
    pics = sorted(F.images, key=lambda x: x.ctime)
    if len(pics) > 1:
        for x in pics[:-1]:
            print(x)
            target_dir = os.path.join(root, to)
            if not os.path.exists(target_dir):
                os.makedirs(target_dir)
            x.move_to(target_dir)

    set_wallpaper(pics[-1].path)


def set_wallpaper(path):
    db = os.path.expanduser("~/Library/Application Support/Dock/desktoppicture.db")
    cmd = ["sqlite3", db, f'update data set value = "{path}"']
    run_shell(cmd) and run_shell(["killall", "Dock"])


if __name__ == "__main__":
    download() and archive_and_set_wp()

3. 设置系统定时更换壁纸

17-02-20更新:通过命令行更新壁纸(见上一步)

这个时间间隔可以设置得小一点,这样更新今天的壁纸后,可以尽快看到效果

4. 定时任务的编写

$ cd ~
$ vi .crontab

输入:

# 每天9、11、13...点,0分或者30分的时候运行这个程序来下载壁纸,归档旧壁纸
0,30 9,11,13,15,19,22 * * * /usr/local/bin/python /Users/garden/Downloads/BingWallpapers/run.py

继续运行:

# 添加定时任务
$ crontab ~/.crontab
# 查看已添加的定时任务
$ crontab -l

附:MacOS 命令行设置屏幕壁纸

# Up to Mountain Lion
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/path/to/picture.jpg"'

# Since Mavericks
sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db "update data set value = '/path/to/picture.jpg'" && killall Dock

https://github.com/herrbischoff/awesome-osx-command-line#wallpaper

comments powered by Disqus