共三个模块
getweather.py #获取天气信息
smtpmail.py #发送邮件
reporter.py #主程序入口,定时发送邮件
- 仅为练手项目
getweather.py
#!/usr/bin/python
# encoding: utf-8
import urllib2
import urllib
import json
class Weather(object):
def weathersettings(self, woeid):
self.woeid = woeid
# woeid,类似城市代码 可以在 http://woeid.rosselliot.co.nz/ 查询
baseurl = "https://query.yahooapis.com/v1/public/yql?"
yql_query = "select wind from weather.forecast where woeid=" + woeid
yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json"
result = urllib2.urlopen(yql_url).read()
data = json.loads(result) # dict类型数据
return data
smtpmail.py
#!/usr/bin/python
# encoding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
class Smtpmail(object):
def mailsettings(self, subject, body):
self.subject = subject
self.body = body
sender = 'xxxx@163.com' # 发送邮件地址
receiver = 'yyy@gmail.com' # 接收邮件地址
smtpserver = 'smtp.163.com' # smtp服务器地址
port = 25 # smtp端口
username = 'xxxx@163.com' # 用户名
password = 'password' # 密码
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = 'xxx<xxx@163.com>'
msg['To'] = "yyy@gmail.com"
smtp = smtplib.SMTP()
# debug, 0为关闭,1为开启
# setsid常驻后台时必须关闭 否则进程会自动kill掉
smtp.set_debuglevel(1)
smtp.connect(smtpserver, port)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
reporter.py
#!/usr/bin/python
# encoding: utf-8
import time
import threading
import logging
from getweather import *
from smtpmail import *
class Reporter(object):
def run_program(self):
weather = Weather()
smtpmail = Smtpmail()
# 获取并格式化当前时间
time_now = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# 判断早中晚
if int(time_now.split()[1][0:2]) < 12:
time_word = 'Morning'
elif int(time_now.split()[1][0:2]) < 18:
time_word = 'Afternoon'
else:
time_word = 'Evening'
# 输入woeid
weather_data = weather.weathersettings('2147986')
# 当前天气
weather_now = weather_data['query']['results']['channel'].keys()[0]
# 华氏度转摄氏度
weather_centigrade = str(int(
(int(weather_data['query']['results']['channel']['wind']['chill']) - 32) / 1.8))
# 标题输出格式
subject = 'Weather Report {}'.format(time_now)
# 正文输出格式
body = '''
Weather Report
-----------------------------
Good {} !
This is the weather report.
This {} is will be {}.
It will {} degrees.
Thank you for listening.
-----------------------------
'''.format(time_word, time_word, weather_now, weather_centigrade)
# 发送邮件
smtpmail.mailsettings(subject, body)
# 日志格式
logging.basicConfig(
level = logging.DEBUG, # 定义输出到文件的log级别
format = '%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定义输出log的格式
datefmt = time_now, # 时间
filename = 'logging.log', # log文件名
filemode = 'a') # 写入模式:“w”覆盖模式,“a”追加模式
console = logging.StreamHandler() # 定义console handler
console.setLevel(logging.INFO) # 定义该handler级别
formatter = logging.Formatter('%(asctime)s %(filename)s : %(levelname)s %(message)s') #定义该handler格式
console.setFormatter(formatter)
logging.getLogger().addHandler(console) # 实例化添加handler
# 输出日志
logging.info('Subject:{}'.format(subject))
logging.info('Body:{}'.format(body))
# 延时器
global timer
reporter = Reporter()
timer = threading.Timer(3600.0, reporter.run_program) #间隔为1小时
timer.start()
if __name__ == "__main__":
reporter = Reporter()
timer = threading.Timer(2.0, reporter.run_program)
timer.start()
Ubuntu后台运行
虚拟机中新安装一个Ubuntu Server,以下为配置过程
sudo -i #提升权限
sudo apt-get update #更新软件列表
sudo apt-get upgrade #更新软件
python -v #查看python版本(没有...)
sudo apt install python3 #安装python3
sudo apt-get install python-pip #安装pip
sudo pip install --upgrade pip #升级pip
cd / #移动到根目录
mkdir pyweather #新建目录pyweather
cd pyweather #移动至pyweather文件夹
vi reporter.py #新建并编辑py文件
cat reporter.py #确认是否有误
vi smtpmail.py
cat smtpmail.py
vi getweather.py
cat getweather.py
ls #确认文件
setsid python reporter.py #常驻后台运行
history #回顾配置过程
后来才发现邮件中的时间不对,需要改时区
date -R #确认时间
dpkg-reconfigure tzdata # 选择时区
date -R #再次确认
参考链接
https://developer.yahoo.com/weather/
https://blog.csdn.net/z_johnny/article/details/50812878
https://blog.csdn.net/qq_18884487/article/details/78254257
https://blog.csdn.net/u011846143/article/details/78274911
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000
https://www.jianshu.com/p/abb2d6e91c1f
https://blog.csdn.net/qq_20480611/article/details/50325653
https://blog.csdn.net/DavyLee2008/article/details/56015573
网友评论