我如何在 While True 循环中放置一些条件

乘风 python 221

原文标题How can i put some condition in While True loop

我在 python 中使用 Schedule 模块来调度我的代码,因此我使用了 While True –

在这里我有四个计划时间。

schedule.every().day.at(schedule_time).do(run_code)
while True:
   schedule.run_pending()
   time.sleep(2)

我在 Telegram 的帮助下运行这段代码。在 Telepot 模块的帮助下

def handle(msg):
    text_data = msg['text']
    if (text_data == 'Start):
        message = initial_message()
        bot.sendMessage(1753352834, "Schedule Code starts running")
        # Schedule_code function is calling for run my entire main code
        schedule_code()
    else:
        bot.sendMessage(1753352834, "Sorry, I don't understand your mean, you should write Start")
MessageLoop(bot, handle).run_as_thread()

当我写在电报开始时,这段代码开始运行,但我想在电报的帮助下停止这段代码,但我不明白怎么做。

我不知道如何停止这个虽然真正的功能 – 我想要,当我在电报上写停止时,我的整个代码都会停止。

if (text_data == 'Stop):
   sys.exit()
else:
    pass

原文链接:https://stackoverflow.com//questions/71463484/how-can-i-put-some-condition-in-while-true-loop

回复

我来回复
  • Yanni2的头像
    Yanni2 评论

    如果你想退出你的程序,你可以使用

    while True:
        quit() #Stops the python script
    

    如果您只想跳出循环,则可以使用

    while True:
        break
    

    但最好的方法是有条件的。你可以使用类似的东西

    stop = False
    while not stop:
        #Do something
        if text_data == "Stop":
            stop = True
    
    2年前 0条评论