只使用while循环

2024-03-28 15:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个简单的程序,每天早上通过电子邮件向我通报我所在城市的天气。目前,它是有效的,但只有一次。使用while循环是可行的,但由于我将其设置为

while time == 0600:
    send my mail etc

很明显,在那一分钟里,我都会收到垃圾邮件。所以我要想办法让事情每24小时发生一次。在

这是我的完整代码(目前只工作一次,直到我重新启动它)。在

^{pr2}$

Tags: 程序sendtime电子邮件myetc垃圾邮件mail
2条回答

为什么不在你发完邮件后马上写一份声明呢?这只会使你脱离循环。然后它将执行程序的其余部分。在

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

首先,你整天运行一个脚本,让它一天只做一次。这是不合逻辑的。你应该在你的操作系统(Win,Linux,Mac)上安排一个任务,这样你的脚本就可以在每天6小时被激活,并删除脚本中的时间条件。在

如果你想变得花哨,创建一个电报机器人,让它在你想要的任何时候,在你的手机上,为你指定的地点向你发送一条消息。在

不过,脚本很容易修复。您使用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')
    ....

相关问题 更多 >