在python中每N次运行一个方法

我试图每 5 秒打印一个句子,我需要向它传递一个参数。


我在用threading


import threading


def printit(whatever):

  threading.Timer(5.0, printit).start()

  print(whatever)


var= "start"

printit(var)

这给了我这个错误


C:\Users\Wei Xi\Desktop>python test.py

start

Exception in thread Thread-1:

Traceback (most recent call last):

  File "C:\Users\Wei Xi\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner

    self.run()

  File "C:\Users\Wei Xi\AppData\Local\Programs\Python\Python38\lib\threading.py", line 1254, in run

    self.function(*self.args, **self.kwargs)

TypeError: printit() missing 1 required positional argument: 'whatever'```



ibeautiful
浏览 217回答 4
4回答

繁花不似锦

threading.Timer构造函数接受各个目标函数 ( ) 的args关键字参数:kwargsclass threading.Timer(interval, function, args=None, kwargs=None)import threadingdef printit(whatever):  threading.Timer(5.0, printit, args=(whatever,)).start()  print(whatever)var= "start"printit(var)示例输出将是(在“无限”打印中):startstartstartstart...

千巷猫影

这是可能的解决方案之一:import threadingdef printit(whatever):     print(whatever)    threading.Timer(5.0, printit, {whatever}).start() var = "start" printit(var)您收到错误是因为您在whatever递归调用printit函数时没有传入(函数参数)。编辑:但是,此解决方案将产生无限数量的线程。如果您想将该进程作为后台任务运行,您可以这样做只使用一个线程。注意:我在这个例子中使用了 2 个参数。import timeimport threadingdef printit(whatever, whatever2, seconds=5):    while True:        print(whatever)        print(whatever2)        time.sleep(seconds)var = "start"var2 = "end"threading.Thread(target=printit, kwargs={"whatever":var, "whatever2":var2, "seconds":5}).start() print("Do something else")输出:startendDo something elsestartendstartend... (repeat start end every 5 seconds)

叮当猫咪

你可以使用时间:def printit(str_):   time.sleep(5)   print(str_)var = "start"while True:     printit(var)

白猪掌柜的

您可以time.sleep()在 while 循环中使用该函数:import timedef printit(whatever, seconds=5):    while True:        print(whatever)        time.sleep(seconds)var= "start"printit(var) # prints "start" every 5 seconds#start#start#start
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python