我在try子句中有一个命令,我知道它会引发异常。我试图在“except”子句中捕获它,但是except子句似乎不承认异常的存在。未处理的异常(即未包含在try子句中)在交互窗口中显示如下:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Andy\software\Turkeys\actions.py", line 234, in annotate
annotation=annotator.ncbo_annotate(thing)
File "C:\Users\Andy\software\Turkeys\annotator.py", line 49, in ncbo_annotate
fh = urllib2.urlopen(submitUrl, postData)
File "C:\32Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "C:\32Python27\lib\urllib2.py", line 406, in open
response = meth(req, response)
File "C:\32Python27\lib\urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "C:\32Python27\lib\urllib2.py", line 444, in error
return self._call_chain(*args)
File "C:\32Python27\lib\urllib2.py", line 378, in _call_chain
result = func(*args)
File "C:\32Python27\lib\urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error
当我将命令放入该列表的第一个文件中的try/except构造中时,“actions.py”,如下所示:
try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this
我希望上面的子句能够捕获在运行ncbo ou annotate函数时生成的“http error:http error 500:internal server error”,但是当我运行上面的函数时,会收到一个错误,即全局名称“httperror”未定义:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Andy\software\Turkeys\actions.py", line 235, in annotate
except HTTPError:
NameError: global name 'HTTPError' is not defined
那是怎么回事?我认为python会引发异常,直到它在try子句中找到一个处理程序或将它吐出未处理的。为什么我的代码不知道httperror是什么,或者,我如何告诉它它是什么,以便它能够处理它?
最佳答案
在使用之前,您可能只需要导入HTTPError
类。尝试在actions.py文件的顶部插入:
from urllib2 import HTTPError
然后,您应该能够按原样使用您的代码。
关于python - NameError:未定义全局名称“HTTPError”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15600707/