Python - 永无止境 time.sleep(1) - 有可能结束吗?

Python - Never-ending time.sleep(1) - Possible to end it?

所以我一直在研究日程安排,终于让它开始工作了。我太兴奋了,没意识到又出现了另一个问题哈哈。但是现在的问题是,只要主要完成,它就不会结束,我真的找不到解决方案。我知道问题出在行 Time.sleep(1) 因为每当我 keyboardInterrput 然后出现错误说 Time.sleep(1) 是 "Issue" 我真的找不到结束它的解决方案。

我正在使用 github 的时间表:Github schedule

while True:
    UserInput = input('To run Schedule task - Press y\nTo run directly - Press n\n')

    if(UserInput == 'y' or UserInput == 'Y'):
        print(Fore.RESET + space)
        TimeUser = input('What time to start script? Format - HH:MM\n')

        schedule.every().day.at(TimeUser).do(main)
        wipe()
        print('Schedule starts at: ''' + TimeUser + ' - Waiting for time...')
        idle = int(round(schedule.idle_seconds()))



        while True:
            schedule.run_pending()
            time.sleep(1)
            idle = int(round(schedule.idle_seconds()))
            if(idle < 6.0) and (idle >= 0.0):
                print('Starting in: ' + str(idle))

    elif(UserInput == 'n' or UserInput == 'N'):
        main()


    print("Wrong input - Try again")

您的代码被封装在 while 循环中,以 true 作为参数。要么你错误地这样做了,要么这是糟糕的结构。就是这个问题。

如果你不想删除 while 循环,那么至少在某处添加一个 break

如果您在构建代码时需要帮助,请转至 Code Review.

您可以使用 for 关键字。 for 语句可以定义您的迭代和停止条件。或者使用 range() 函数迭代您的数字序列。

习惯了传统的 if-then-else 语句,break 语句会让您跳出 while 循环。它需要与你最里面的 forwhile 循环。您的 else 子句需要属于您的 for 循环,而不是 if 语句的一部分。 continue 语句将使您的循环向前移动。

这里有例子:https://docs.python.org/3/tutorial/controlflow.html