Python计时器“NoneType"对象不可调用错误 [英] Python timer 'NoneType' object is not callable error
问题描述
我想做一个程序,每 10 秒检查一次给定的 url
I want to make a program which is checks the given url for every 10 seconds
def listener(url):
print ("Status: Listening")
response = urllib.request.urlopen(url)
data = response.read()
text = data.decode('utf-8')
if text == 'Hello World. Testing!':
print("--Action Started!--")
t = Timer(10.0,listener('http://test.com/test.txt'))
t.start()
这里是输出:
Status: Listening
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib/python3.4/threading.py", line 1186, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
运行一次,10秒后出现错误
It runs the function for one time, after 10 seconds the error appears
推荐答案
目前,您的 listener
函数调用的结果正在提供给 Timer
,结果是 None
,因为您需要进行显式返回,以便您的 Timer
可以进行操作.
Currently, the result of your listener
function call is being given to Timer
, which is resultantly None
, as you need to make an explicit return so your Timer
has something to operate on.
您必须将 listener()
的参数放在另一个参数中,就像这样.请注意,args
必须是一个序列,因此带逗号的元组放在 url
之后.如果没有这个元组,您会将 'http://test.com/test.txt'
中的每个字符作为参数传递给 listener
.
You have to place the argument for your listener()
in another parameter, like this. Note that args
must be a sequence, thus the tuple with the comma placed after your url
. Without this tuple, you are passing each individual character from 'http://test.com/test.txt'
as an argument to listener
.
t = Timer(10.0,listener,args=('http://test.com/test.txt',))
正如您在文档此处中所见,参数必须作为第三个参数传递.
As you can see in documentation here, arguments must be passed as a third parameter.
这篇关于Python计时器“NoneType"对象不可调用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!