如何从另一个函数中停止一个函数?

How to stop a function from another function?

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()

添加停止标志:

  • 向主函数添加逻辑:当停止标志为真时,主函数应该return
  • 在 stopfunc 中设置停止标志为 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       

...