如何停止另一个功能?

问题描述

TOKEN = 'token'
bot = telebot.TeleBot(TOKEN)

def main():
   for i in range(0,100):
      print(i)

@bot.message_handler(commands=['start'])
def start(message):
  main()

@bot.message_handler(commands=['stop'])
def stopfunc(message):
   #how to stop the function main() ?

while True:
   bot.polling()

解决方法

添加停止标志:

  • 向主功能添加逻辑:当停止标志为True时,主功能应返回
  • 在stopfunc中将stop标志设置为True
stop = False
def main():
   global stop
   for i in range(0,100):
       if stop:
          break
       print(i)
    
@bot.message_handler(commands=['stop'])
def stopfunc(message):
    global stop
    stop = True       

...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...