猿问

在某些情况下重复执行python函数并停止该函数的最佳方法是什么?

我想每5秒重复执行一次函数,同时从用户那里接受输入,并基于输入停止执行吗?前任:


def printit():

   t=threading.Timer(3.0,printit)

   t.start()

   n=str(input())

   if(n=='rajesh'):

        t.cancel()

   else:

      #I want to continue the execution here


侃侃无极
浏览 307回答 3
3回答

慕桂英4014372

这应该有帮助import time#use a While loopWhile True:      #request said user input      x= input("Please Press 1 to continue Or 2 to Exit")      #then an if statement       if x==1:            #call your function            printit()            time.sleep(5)      else:break这应该可以解决

莫回无

如果您真的想使用线程,那么这应该可以工作:import threadingimport timedef worker():    while True:        user_input = input("Enter text:")        if user_input == 'rajesh':            break        else:            time.sleep(5)thread = threading.Thread(target=worker, daemon=True)thread.start()thread.join()

MYYA

这应该有帮助#request said user inputx= input("Please Press 1 to continue Or 2 to Exit")#use a While loopWhile True:      #then an if statement       if x==1:            #call your function            printit()      else:break这应该可以解决
随时随地看视频慕课网APP

相关分类

Python
我要回答