为什么我的变量值没有传递给python中的finally块

Cla*_*ied 1 python exception httplib python-2.7

这是为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)
Run Code Online (Sandbox Code Playgroud)

这是我们得到的输出,如果它与http 200代码一起使用:

got a 200 http response.  everything seems good this is the code we got: 200
Run Code Online (Sandbox Code Playgroud)

这是我们获得的输出,如果它获得异常

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
Run Code Online (Sandbox Code Playgroud)

编辑:如果我等了5分钟,并打了一个问题的网站,那么我得到响应代码/正确的输出.这里可能有第二个问题,为什么网站花了这么长时间才能返回http 500代码(工作5分钟).

mgi*_*son 8

如果发生异常,则赋值语句(resp = conn.getresponse().status)永远不会运行或永远不会结束.1 在这种情况下,当finally子句运行时,您将收到错误,因为resp它从未设置为任何内容.

根据用途,它看起来像你想要使用else而不是finally. finally无论如何都会运行,但else只有在try套件没有例外的情况下才能运行.

1考虑发生的异常conn.getresponse- 由于引发了异常,因此conn.getresponse永远不会返回任何内容,因此没有值绑定到resp左侧.