前景提要
由于楼主比较懒,想着如果未来几天要下雨,那就自动提醒我,不下雨就别提醒我,通知通过 macos 的通知提醒给用户
编写脚本
脚本代码如下 ak 为百度地图的秘钥,可以自己去申请一个,个人用免费的就够用了 #!/usr/local/bin/python3 # coding=utf-8 from urllib import request, parse import json from subprocess import Popen, PIPE if __name__ == '__main__': # 百度地图的 ak,需要自己去申请 ak='xxxx' # 获取地理位置 locationUrl = "http://api.map.baidu.com/location/ip?ak=%s"%ak response = request.urlopen(locationUrl) read = response.read() info = json.loads(read) address = info["content"]["address"] # 获取天气 url = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=%s&location="%ak response = request.urlopen(url + parse.quote(address)) response_read = response.read() weater = json.loads(response_read) weater_data = weater["results"][0]["weather_data"] # 判断是否下雨 hasWeater = False msg = '' msgDetail = "" day = {1: '今天', 2: '明天', 3: '后天', 4: '大后天'} i = 1 for we in weater_data: encode = we['weather'] if '雨' in encode: hasWeater = True msg += day[i] + ',' msgDetail += day[i] + ' : ' + encode + ' ' i += 1 msg += '有雨' args = ['display notification "' + msgDetail + '" with title "天气预报" subtitle "' + msg + '"'] if hasWeater: p = Popen(['osascript', '-e'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
添加定时器,定时检查
crontab -e 写入 0 9,11,15,18 * * * python3 /User/.../weather.py
注: 文件地址需要全路径 我这里设置的是 9,11,15,18 点检查下,可以自己改
设置权限
macos 新版本需要给 cron 弄下权限,这个当时找了我好久
系统偏好设置 > 安装性与隐私 > 完全磁盘访问权限 > 隐私 > 完全的磁盘访问权限 把 /usr/sbin/cron 拖进去就好