我想运行一个代码,每 5 秒运行一个带有参数的函数(例如 greet(h))。我尝试使用threading 但它不起作用。它只执行一次。请参阅下面的代码和错误:
import threading
oh_hi = "Hi guys"
def greeting(hello):
print "%s" % hello
threading.Timer(1, greeting(oh_hi)).start()
错误如下所示:
> >>> ================================ RESTART
> ================================
> >>> Hi guys
> >>> Exception in thread Thread-1: Traceback (most recent call last):
> File "C:\Python27\lib\threading.py",
> line 530, in __bootstrap_inner
> self.run() File "C:\Python27\lib\threading.py", line
> 734, in run
> self.function(*self.args, **self.kwargs) TypeError: 'NoneType' object is not callable
请提供帮助。
谢谢
最佳答案
正如其他人指出的那样,错误是因为您没有将正确的参数传递给 threading.Timer()
方法。更正将在 5 秒后运行您的函数一次。有很多方法可以让它重复。
安object-oriented方法是派生一个新的 threading.Thread
子类。虽然可以创建一个专门做你想做的事情——即 print "%s" % hello
-- 制作一个更通用的、参数化的、将调用在其实例化期间传递给它的函数的子类(就像 threading.Timer()
)稍微困难一点。如下图所示:
import threading
import time
class RepeatEvery(threading.Thread):
def __init__(self, interval, func, *args, **kwargs):
threading.Thread.__init__(self)
self.interval = interval # seconds between calls
self.func = func # function to call
self.args = args # optional positional argument(s) for call
self.kwargs = kwargs # optional keyword argument(s) for call
self.runable = True
def run(self):
while self.runable:
self.func(*self.args, **self.kwargs)
time.sleep(self.interval)
def stop(self):
self.runable = False
def greeting(hello):
print hello
thread = RepeatEvery(3, greeting, "Hi guys")
print "starting"
thread.start()
thread.join(21) # allow thread to execute a while...
thread.stop()
print 'stopped'
输出:
# starting
# Hi guys
# Hi guys
# Hi guys
# Hi guys
# Hi guys
# Hi guys
# Hi guys
# stopped
除了重写基础 threading.Thread
类(class)的__init__()
和 run()
方法,一个stop()
添加了方法以允许在需要时终止线程。我还简化了 print "%s" % hello
在你的greeting()
功能只是print hello
.
关于python - 在python中每X秒执行一个函数(带参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5564009/