Python 3.3:使用Timer捕获HTTPError

时间:2013-03-21 05:47:04

标签: python

我一直在尝试研究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')

1 个答案:

答案 0 :(得分:1)

构建Timer时,您正在调用打印功能。构建Timer的正确方法是Timer(2.0, print, 'Time Out Error')