为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

侃侃无极 2021-04-01 10:07:06
我想每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
查看完整描述

3 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

这应该有帮助


import time

#use a While loop

While 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

这应该可以解决


查看完整回答
反对 回复 2021-04-13
?
莫回无

TA贡献1865条经验 获得超7个赞

如果您真的想使用线程,那么这应该可以工作:


import threading

import time


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


查看完整回答
反对 回复 2021-04-13
?
MYYA

TA贡献1868条经验 获得超4个赞

这应该有帮助


#request said user input

x= input("Please Press 1 to continue Or 2 to Exit")

#use a While loop

While True:

      #then an if statement 

      if x==1:

            #call your function

            printit()

      else:break

这应该可以解决


查看完整回答
反对 回复 2021-04-13
  • 3 回答
  • 0 关注
  • 306 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号