【发布时间】:2016-02-13 02:41:56
【问题描述】:
我的问题是 python urllib 错误对象的错误处理。我无法读取错误消息,同时仍将其完整地保存在错误对象中,以便稍后使用。
response = urllib.request.urlopen(request) # request that will raise an error
response.read()
response.read() # is empty now
# Also tried seek(0), that does not work either.
所以这就是我打算使用它的方式,但是当异常冒泡时,.read() 第二次为空。
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
self.log.exception(err.read())
raise err
我尝试对 err 对象进行深度复制,
import copy
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
err_obj_copy = copy.deepcopy(err)
self.log.exception(
"Method:{}\n"
"URL:{}\n"
"Data:{}\n"
"Details:{}\n"
"Headers:{}".format(method, url, data, err_obj_copy.read(), headers))
raise err
但复制无法进行深度复制并引发错误 -
TypeError: __init__() missing 5 required positional arguments: 'url', 'code', 'msg', 'hdrs', and 'fp'.
如何阅读错误消息,同时仍将其完整地保存在对象中?
我确实知道如何使用 requests 来做到这一点,但我被遗留代码困住了,需要让它与 urllib 一起工作
【问题讨论】:
标签: python python-3.x error-handling urllib