【发布时间】:2016-07-08 03:31:09
【问题描述】:
这适用于 python 2.7.10 也许我没有正确使用 try..except..finally 阻止。
我需要检查从网页获得的 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 代码时得到的输出:
got a 200 http response. everything seems good this is the code we got: 200
这是我们遇到异常时得到的输出
got some exception
Traceback (most recent call last):
File "monitorAlive.py", line 27, in <module>
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 分钟,然后在网站上遇到问题,那么我会得到响应代码/正确的输出。这里可能还有第二个问题,为什么网站需要这么长时间才能返回 http 500 代码(5 分钟才能工作)。
【问题讨论】:
-
顺便说一句,
else:足以代替if resp != 200: -
看起来不太对劲。该错误仅显示
except块中 4 个print语句中的第一个的输出。
标签: python python-2.7 exception httplib