【发布时间】:2013-02-18 14:35:07
【问题描述】:
我正在使用 urllib.request.urlopen() 从我正在尝试测试的 Web 服务获取。
这会返回一个 HTTPResponse 对象,然后我通过 read() 来获取响应正文。
但我总是从 socket.py 中看到关于未关闭套接字的 ResourceWarning
下面是相关函数:
from urllib.request import Request, urlopen
def get_from_webservice(url):
""" GET from the webservice """
req = Request(url, method="GET", headers=HEADERS)
with urlopen(req) as rsp:
body = rsp.read().decode('utf-8')
return json.loads(body)
这是程序输出中出现的警告:
$ ./test/test_webservices.py
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py:359: ResourceWarning: unclosed <socket.socket object, fd=5, family=30, type=1, proto=6>
self._sock = None
.s
----------------------------------------------------------------------
Ran 2 tests in 0.010s
OK (skipped=1)
如果我可以对 HTTPResponse(或请求?)做任何事情以使其干净地关闭其套接字, 我真的很想知道,因为这段代码是用于我的单元测试的;我不喜欢 忽略任何地方的警告,尤其是不在那儿。
【问题讨论】:
-
我无法在 Python 3.3.1 上重现它。你能在最新的 Python 版本上测试它吗?有几个与closing the socket(超时时的资源警告)和
"Connection: close"response header(根据标头显示不同的代码路径)相关的错误。
标签: python python-3.x warnings urllib