我正在制作一个简单的程序,每天早上通过电子邮件向我发送我所在城市的天气。目前,它有效,但只有一次。使用while循环可以工作,但是因为我将它设置为,
while time == 0600:
send my mail etc
现在很明显,在整个那一分钟内,我就会收到垃圾邮件。因此,我需要找到一种方法,每24小时发生一次。
这是我的完整代码(目前只运行一次,直到我重新启动它)。
import smtplib, pywapi, datetime
weather = True
loopmsg = True
loopmsg1 = True
def send():
loopmsg = True
loopmsg1 = True
global weather
while weather == True:
if loopmsg == True:
print('Initial Loop Initiated')
loopmsg = False
time = datetime.datetime.now()
time = str(time)
time = time[11:]
time = time[:-10]
time = time.replace(":", "")
time = int(time)
fromaddr = 'xxx'
toaddrs = 'xxx'
while time == 0600:
print('Time is correct')
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
msg = "It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "°C in Your City."
msg = msg.encode('utf-8')
# Credentials (if needed)
username = 'xxx'
password = 'xxx'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print('Sent')
#weather = False
#while weather == False:
# if loopmsg1 == True:
# print('Second Loop Initiated')
# loopmsg1 = False
# while time > 0600:
# send()
send()
答案 0 :(得分:2)
首先,你整天都在运行一个脚本,它每天只能做一次。这是不合逻辑的。您应该在您的操作系统上安排任务(Win,Linux,Mac - 他们都有办法安排任务),以便您的脚本每天6小时激活;并删除脚本中的时间条件。
如果您想获得想象力,请创建一个Telegram机器人,让它随时在您的手机上为您指定的位置向您发送消息。
然而,该脚本很容易修复。您将while
循环用作if
。只需添加一个变量即可使其仅发送一次电子邮件。
if time == 0500:
send_email = True
if send_email and time == 0600:
print('Time is correct')
send_email = False
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
....
答案 1 :(得分:0)
为什么不在发送电子邮件后立即发表休息声明?这只会让你突破循环。然后它将执行程序的其余部分。
while time == 0600:
print('Time is correct')
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
msg = "It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "°C in Your City."
msg = msg.encode('utf-8')
# Credentials (if needed)
username = 'xxx'
password = 'xxx'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print('Sent')
break