threading.Timer() [英] threading.Timer()
问题描述
我必须在网络课程中编写一个类似于选择性重复但需要计时器的程序.在谷歌搜索后,我发现 threading.Timer 可以帮助我,我写了一个简单的程序只是为了测试 threading.Timer 是如何工作的:
i have to write a program in network course that is something like selective repeat but a need a timer. after search in google i found that threading.Timer can help me, i wrote a simple program just for test how threading.Timer work that was this:
import threading
def hello():
print "hello, world"
t = threading.Timer(10.0, hello)
t.start()
print "Hi"
i=10
i=i+20
print i
这个程序运行正常.但是当我尝试以提供如下参数的方式定义 hello 函数时:
this program run correctly. but when i try to define hello function in a way that give parameter like:
import threading
def hello(s):
print s
h="hello world"
t = threading.Timer(10.0, hello(h))
t.start()
print "Hi"
i=10
i=i+20
print i
输出是:
hello world
Hi
30
Exception in thread Thread-1:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 726, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
我不明白这是什么问题!有人可以帮我吗?
i cant understand what is the problem! can any one help me?
推荐答案
你只需要把 hello
的参数放到函数调用的一个单独的项目中,像这样,
You just need to put the arguments to hello
into a separate item in the function call, like this,
t = threading.Timer(10.0, hello, [h])
这是 Python 中的常用方法.否则,当你使用Timer(10.0, hello(h))
时,这个函数调用的结果会传递给Timer
,也就是None
因为 hello
没有明确返回.
This is a common approach in Python. Otherwise, when you use Timer(10.0, hello(h))
, the result of this function call is passed to Timer
, which is None
since hello
doesn't make an explicit return.
这篇关于threading.Timer()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!