Python计时器'NoneType'对象不可调用错误

时间:2015-03-29 15:27:06

标签: python multithreading

我想制作一个每隔10秒检查一次给定网址的程序

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秒后出现错误

1 个答案:

答案 0 :(得分:5)

目前,listener函数调用的结果是Timer,结果是None,因为您需要明确返回Timer有什么可以操作的。

您必须将listener()的参数放在另一个参数中,如下所示。请注意,args必须是序列,因此在url之后放置逗号的元组。如果没有这个元组,您将每个字符从'http://test.com/test.txt'作为参数传递给listener

t = Timer(10.0,listener,args=('http://test.com/test.txt',))

正如您在文档here中看到的那样,参数必须作为第三个参数传递。