RuntimeWarning:启用 tracemalloc 以使用 asyncio.sleep 获取对象分配回溯
Posted
技术标签:
【中文标题】RuntimeWarning:启用 tracemalloc 以使用 asyncio.sleep 获取对象分配回溯【英文标题】:RuntimeWarning: Enable tracemalloc to get the object allocation traceback with asyncio.sleep 【发布时间】:2019-01-08 08:55:58 【问题描述】:尝试使用信号量来控制异步请求以控制对目标主机的请求,但我收到以下错误,我认为这意味着我的 asycio.sleep()
实际上并没有在睡觉。我怎样才能解决这个问题?我想为每个目标 URL 的请求添加延迟。
错误:
RuntimeWarning: coroutine 'sleep' was never awaited
Coroutine created at (most recent call last)
File "sephora_scraper.py", line 71, in <module>
loop.run_until_complete(main())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete
self.run_forever()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
self._run_once()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
handle._run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "makeup.py", line 26, in get_html
asyncio.sleep(delay)
asyncio.sleep(delay)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
代码:
import sys
import time
import asyncio
import aiohttp
async def get_html(semaphore, session, url, delay=6):
await semaphore.acquire()
async with session.get(url) as res:
html = await res.text()
asyncio.sleep(delay)
semaphore.release()
return html
async def main():
categories =
"makeup": "https://www.sephora.com/shop/"
semaphore = asyncio.Semaphore(value=1)
tasks = []
async with aiohttp.ClientSession(loop=loop, connector=aiohttp.TCPConnector(ssl=False)) as session:
for category, url in categories.items():
# Get HTML of all pages
tasks.append(get_html(semaphore, session, url))
res = await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
【问题讨论】:
还可以使用async with
或至少try/except
与信号量,如here 所示。它会保证即使出现异常也会释放信号量。
【参考方案1】:
asyncio.sleep(delay)
改成:
await asyncio.sleep(delay)
asyncio.sleep
是 coroutine,应该等待。
【讨论】:
以上是关于RuntimeWarning:启用 tracemalloc 以使用 asyncio.sleep 获取对象分配回溯的主要内容,如果未能解决你的问题,请参考以下文章
RuntimeWarning:协程“Messageable.send”从未等待 python.py
Pycharm 更新到 2016.2 后导入 RuntimeWarning
Django 中 DateField 的 RuntimeWarning