【问题标题】:Why doesn't my variable value get passed to the finally block in python为什么我的变量值没有传递给python中的finally块
【发布时间】: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


【解决方案1】:

如果发生异常,则赋值语句 (resp = conn.getresponse().status) 要么永远不会运行,要么永远不会完成。1 在这种情况下,当 finally 子句运行时,你会得到一个错误因为resp 从未设置为任何值。

根据使用情况,看起来你想使用 else 而不是 finallyfinally 无论如何都会运行,但 else 只会在 try 套件无异常完成时运行。

1考虑在conn.getresponse 中发生的异常——由于引发了异常,conn.getresponse 永远不会返回任何东西,因此没有任何价值绑定到左侧的resp

【讨论】:

    【解决方案2】:

    解决方案是在 "try" 子句之前将 None 分配给 "resp"。如下所示。

    resp = None
    try:
    

    当你运行 conn.request("GET", "/alive") 时,如果超时,这可能会导致异常,然后你的代码将进入 "except" 然后 "finally" 子句。但是变量没有分配,所以出错了。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      相关资源
      最近更新 更多