我正在開發一個簡單的程序,每天早上給我發電子郵件給我的城市的天氣。目前,它工作,但只有一次。使用while循環工作,但因爲我有它設置爲,只使用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()
爲什麼'while','if'只運行一次?無論如何:1.在send例程中添加一個標誌'sentMail'並將其設置爲'True'。 2.'sentMail'爲'True'時不發送。 3.添加一個新的'if time == 0601',將'sentMail'重置爲'False'。 – usr2564301