相关疑难解决方法(0)

使用Python 3中的urllib进行socket ResourceWarning

我正在使用urllib.request.urlopen()从我正在尝试测试的Web服务获取GET.

这将返回一个HTTPResponse对象,然后我读取()以获取响应主体.

但我总是看到一个关于来自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)
Run Code Online (Sandbox Code Playgroud)

这是程序输出中出现的警告:

$ ./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)
Run Code Online (Sandbox Code Playgroud)

如果我可以对HTTPResponse(或Request?)做任何事情让它干净地关闭它的套接字,我真的很想知道,因为这个代码是我的单元测试; 我不喜欢在任何地方忽略警告,但尤其不在那里.

python warnings urllib python-3.x

8
推荐指数
1
解决办法
2151
查看次数

标签 统计

python ×1

python-3.x ×1

urllib ×1

warnings ×1