这是针对python2.7.10的
也许我没有使用try…except…finally block correct。在
我需要检查我从网页上得到的HTTP响应代码。
如果我得到200码,一切正常。如果我有其他代码,报告什么代码。在
如果我得到一个200个HTTP代码就可以了。
如果我得到一个异常,由于某种原因,它会给我一个UnboundedLocalError,声明我的变量没有被引用。如何在finally块中识别变量?在
我的代码是:try:
conn = httplib.HTTPConnection(host, port=9000)
conn.request("GET", "/alive")
resp = conn.getresponse().status
except Exception as e:
print "got some exception"
print "exception " + e
print "Exception msg: " + e.message
print "Args for exception: " + e.args
finally:
if resp == 200:
print "got a 200 http response. everything seems good"
if resp != 200:
print "didn't get a 200 http response. something wrong"
print "this is the code we got: " + str(resp)
这是我们得到的输出,如果它与http 200代码一起工作:
^{pr2}$
这是我们在异常情况下得到的输出got some exception
Traceback (most recent call last):
File "monitorAlive.py", line 27, in
main()
File "monitorAlive.py", line 24, in main
get_status_code(host)
File "monitorAlive.py", line 16, in get_status_code
if resp == 200:
UnboundLocalError: local variable 'resp' referenced before assignment
编辑:如果我等了5分钟,发现网站有问题,我就会得到响应代码/正确的输出。这里可能还有第二个问题,为什么网站要花这么长时间返回http500代码(5分钟才能工作)。在