【问题标题】:How to stop a function from another function?如何从另一个函数中停止一个函数?
【发布时间】:2020-09-06 10:14:27
【问题描述】:
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()

【问题讨论】:

  • 实现这一点的一种方法是线程化,但我不能建议这样做,因为我不知道你究竟需要实现什么。但是为什么不在主函数中使用“if-else”语句呢?你有什么理由不能?

标签: python function telegram-api


【解决方案1】:

添加停止标志:

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

...

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多