我一直在尝试研究python,我想尝试捕捉服务器超时错误(以防我的互联网连接中断或其他情况)并添加一个计时器,使进程停止X秒(在我下面的代码中是2 秒)然后尝试再次继续该过程。尽管我相信我的逻辑是正确的(如果我错了,请纠正我),但我收到一个错误消息
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python33\lib\threading.py", line 639, in _bootstrap_inner
self.run()
File "C:\Python33\lib\threading.py", line 825, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
我不太明白为什么我的计时器似乎触发和错误。这是我的代码:
import urllib.request
from threading import Timer
req = urllib.request.Request('http://www.nowebsitecontainsthisaddress.com')
def ServerTimeOut(e):
timer_rest = Timer(2.0, print('Time Out Error:'))
timer_rest.start()
print (e.reason)
while timer_rest.is_alive():
pass
while True:
try:
url = urllib.request.urlopen(req)
break
except urllib.error.HTTPError as e:
ServerTimeOut(e)
req = urllib.request.Request('http://www.google.com')
except urllib.error.URLError as e:
ServerTimeOut(e)
req = urllib.request.Request('http://www.google.com')
使用的操作系统是windows7
更新:嗨,伙计们,我尝试将我的代码调整为这个,并且不再返回错误。我确实希望有人可以让我了解为什么会引发错误。谢谢^^,
import urllib.request
from threading import Timer
req = urllib.request.Request('http://www.nowebsitecontainsthisaddress.com')
def printMessage():
print('Time Out Error:')
def ServerTimeOut(e):
timer_rest = Timer(2.0, printMessage)
timer_rest.start()
print (e.reason)
while timer_rest.is_alive():
pass
while True:
try:
url = urllib.request.urlopen(req)
break
except urllib.error.HTTPError as e:
ServerTimeOut(e)
req = urllib.request.Request('http://www.google.com')
except urllib.error.URLError as e:
ServerTimeOut(e)
req = urllib.request.Request('http://www.google.com')