gpt4 book ai didi

python - 名称错误 : global name 'HTTPError' is not defined

转载 作者:太空狗 更新时间:2023-10-29 16:59:06 24 4
gpt4 key购买 nike

我在 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

当我将命令放入该列表的第一个文件“actions.py”中的 try/except 构造中时,如下所示:

try:
annotation=annotator.ncbo_annotate(thing)
except HTTPError:
...do some things with this

当我运行 ncbo_annotate 函数时,我希望上面的子句会捕获正在生成的“HTTPError:HTTP 错误 500:内部服务器错误”,但是当我运行上面的代码时,我收到一个错误,说全局名称“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 是什么,或者我如何告诉它它是什么以便它可以处理它?

最佳答案

在 Python 3 中是:

from urllib.error import HTTPError

关于python - 名称错误 : global name 'HTTPError' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com