python合法的变量名finally,为什么我的变量值不能传递给python中的finally块

This is for python 2.7.10

Perhaps I'm not using the try..except..finally block correctly.

I need to check on the HTTP response code I get from a webpage.

If I get a 200 code, everything is working. If I get any other code, report what code.

It works fine if I get a 200 HTTP code.

If I get an exception, for some reason, it gives me an UnboundedLocalError, stating my variable isn't referenced. How do I get my variable to be recognized in the finally block?

Here's my code:

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)

This is the output we get if it works with a http 200 code:

got a 200 http response. everything seems good this is the code we got: 200

This is the output we get if it gets an exception

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

Edit: If I wait like 5 min, and hit the website with a problem, then I get the response code / proper output. There might be a second question here as to why the website is taking so long to return the http 500 code (5 min to work).

解决方案

If an exception happens, then the assignment statement (resp = conn.getresponse().status) either never runs or never finishes.1 In that case, when the finally clause runs, you'll get an error because resp was never set to anything.

Based on the usage, it looks to me like you want to use else instead of finally. finally will run no matter what, but else will only run if the try suite finished without an exception.

1Consider an exception that happens in conn.getresponse -- Since an exception was raised, conn.getresponse never returns anything so there is no value to be bound to the resp on the left hand side.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值