2016-04-24 99 views
-1

我正在開發一個簡單的程序,每天早上給我發電子郵件給我的城市的天氣。目前,它工作,但只有一次。使用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() 
+1

爲什麼'while','if'只運行一次?無論如何:1.在send例程中添加一個標誌'sentMail'並將其設置爲'True'。 2.'sentMail'爲'True'時不發送。 3.添加一個新的'if time == 0601',將'sentMail'重置爲'False'。 – usr2564301

回答

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 
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') 
    ....