如何停止循环中的操作?

2024-09-29 23:30:51 发布

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

我试图创建一个脚本,自动打开我的在线课程。我写了这段代码:

import webbrowser
import datetime
import time

now = time.strftime("%D, %H:%M")

lesson1 = "03/09/21, 15:38"
lesson2 = "03/10/21, 15:39"
lesson3 = "03/10/21, 15:40"

while True:
    while now != lesson1 and now != lesson2 and now != lesson3:
        print ("Waiting, the current time is " + now)
        now = time.strftime("%D, %H:%M")
        time.sleep(1)

    if now == lesson1:
        print ("LESSON IS OPENING :D")
        webbrowser.open("https://google.com")

    if now == lesson2:
        print ("LESSON IS OPENING :D")
        webbrowser.open("https://google.com")

    if now == lesson3:
        print ("LESSON IS OPENING :D")
        webbrowser.open("https://google.com")

现在,问题是第一个if语句被无限执行,我想让它只执行一次,而不是等到现在==lesson2,然后执行第二个if等等


Tags: httpsimportiftimeisgoogleopennow
2条回答

问题是在每次迭代中,您都要检查当前时间是否等于课程时间,这会导致程序多次打开浏览器。由于您使用的是hours/minutes,因此在当前课程开始后让程序睡眠1分钟会阻止它

样本输入:

import webbrowser
import datetime
import time

now = time.strftime("%D, %H:%M")
print("Current Time   ", now)

lesson1 = "03/10/21, 11:14"
lesson2 = "03/10/21, 11:15"
lesson3 = "03/10/21, 11:16"


while True:
    while now != lesson1 and now != lesson2 and now != lesson3:
        print ("Waiting, the current time is " + now)
        now = time.strftime("%D, %H:%M")
        time.sleep(1)
        
    if now == lesson1:
        print("Opening Google")
        webbrowser.open("https://google.com")
        time.sleep(60)
        now = time.strftime("%D, %H:%M")

    if now == lesson2:
        print("Opening Youtube")
        webbrowser.open("https://youtube.com")
        time.sleep(60)
        now = time.strftime("%D, %H:%M")

    if now == lesson3:
        print("Opening Facebook")
        webbrowser.open("https://facebook.com")
        time.sleep(60)
        now = time.strftime("%D, %H:%M")

样本输出:

Current Time   03/10/21, 11:13
Waiting, the current time is 03/10/21, 11:13
Opening Google
Opening Youtube
Opening Facebook

您似乎希望将代码安排在特定时间运行。我建议使用APScheduler库。非常容易使用,而且效率很高

相关问题 更多 >

    热门问题