同一段代码不同环境运行结果不同。
下面一段代码用来实现在家里宽带外网IP地址改变后,向指定邮箱发送最新的外网IP地址,5分钟检查一次,如果发生变化,则发送邮件:#! /usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import time
from email.mime.text import MIMEText
from json import load
from urllib2 import urlopen
mailto_list=['702730136@'] #收件人(列表)
mail_host="smtp. #使用的邮箱的smtp服务器地址,这里是163的smtp地址
mail_user="XXXX" #用户名
mail_pass="XXXXXX" #密码
mail_postfix=" #邮箱的后缀,搜狐
def send_mail(to_list,sub,content):
me="hello"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list) #将收件人列表以‘;’分隔
try:
server = smtplib.SMTP()
server.connect(mail_host) #连接服务器
server.login(mail_user,mail_pass) #登录操作
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
#下面开始获取外网IP地址
url = load(urlopen('https://'))
a1=url['ip']
a2=a1
send_mail(mailto_list,"最新外网地址",a1)
while True:
time.sleep(300)
url = load(urlopen('https://'))
a1=url['ip']
if a1!=a2:
if send_mail(mailto_list,"最新外网地址",a1):
a2=a1
print "IP地址变更,OK已经成功发送邮件!"
else:
print "IP地址变更,ERROR发送邮件不成功!"
代码在Python 2.7 win7环境下运行正常,开始运行发送一个邮件,然后我断掉光猫电源重启,5分钟内会发送邮件,内容为新外网IP地址。但是,我在树莓派centOS(也是Python 2.7版本)环境里面运行则会出现不一样的结果:第一次开始运行,正常发送一个邮件。断掉光猫电源重启,程序出错。再次运行,首次邮件发送就出错,提示内容如下:
[root@localhost ~]# python /root/sendmail.py
Traceback (most recent call last):
File "/root/sendmail.py", line 32, in <module>
url = load(urlopen('https://'))
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1258, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/usr/lib/python2.7/urllib2.py", line 1214, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 22] Invalid argument>
[root@localhost ~]#
我看了一下,问题都出在这里url = load(urlopen('https://')),但是我不知道为什么在树莓派centOS里面运行的时候,第一次执行这一句正常,第二次执行的时候出错。请大家帮忙看看,发送邮件的用户名和密码我都隐藏了,但是发送邮件的操作是正常的。
[此贴子已经被作者于2018-6-29 23:22编辑过]