RuntimeError: Event loop is closed (and I don't know why)
RuntimeError: Event loop is closed (and I don't know why)
我知道,这可能已经被问了一百次了,但我仍然不明白为什么最后总是会出现错误。
import asyncio
import aiohttp
async def read_index_page():
async with aiohttp.ClientSession() as session:
async with session.get('https://some/api/url') as resp:
print(resp.status)
async def main():
loop = asyncio.get_event_loop()
task = loop.create_task(read_index_page())
await asyncio.gather(task)
if __name__ == '__main__':
asyncio.run(main())
这报告了众所周知的 运行事件外观的时间错误已关闭。我 运行 这段代码在 Windows 10 机器上。
从我的角度来看,我做的事情是正确的,但我完全是使用 asyncio 的初学者。所以,请温柔一点。 :)
问候,托马斯
尝试为您的应用程序设置另一个循环实现,另一方面我应该说我的 Windows 10 Home 没有错误,在 Python 3.6 上测试(使用 Aiohttp 3.4。 4) 和 Python 3.9。 (使用 Aiohttp 3.7.4.post())
import asyncio
from aiohttp import ClientSession
URL = "http://..."
async def send_req(session: ClientSession):
async with session.get(URL) as resp:
if resp.status == 200:
r = await resp.json()
print(r)
else:
print(resp.status)
async def main():
# check what loop is really running in our Main Thread now
loop = asyncio.get_running_loop()
print(loop)
# no need to create ClientSession for all send_req, you need only one ClientSession
async with ClientSession() as session:
# asyncio gather creates tasks itself, no need to create tasks outside
await asyncio.gather(*[send_req(session) for _ in range(8)])
if __name__ == '__main__':
# set another loop implementation:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
我知道,这可能已经被问了一百次了,但我仍然不明白为什么最后总是会出现错误。
import asyncio
import aiohttp
async def read_index_page():
async with aiohttp.ClientSession() as session:
async with session.get('https://some/api/url') as resp:
print(resp.status)
async def main():
loop = asyncio.get_event_loop()
task = loop.create_task(read_index_page())
await asyncio.gather(task)
if __name__ == '__main__':
asyncio.run(main())
这报告了众所周知的 运行事件外观的时间错误已关闭。我 运行 这段代码在 Windows 10 机器上。
从我的角度来看,我做的事情是正确的,但我完全是使用 asyncio 的初学者。所以,请温柔一点。 :)
问候,托马斯
尝试为您的应用程序设置另一个循环实现,另一方面我应该说我的 Windows 10 Home 没有错误,在 Python 3.6 上测试(使用 Aiohttp 3.4。 4) 和 Python 3.9。 (使用 Aiohttp 3.7.4.post())
import asyncio
from aiohttp import ClientSession
URL = "http://..."
async def send_req(session: ClientSession):
async with session.get(URL) as resp:
if resp.status == 200:
r = await resp.json()
print(r)
else:
print(resp.status)
async def main():
# check what loop is really running in our Main Thread now
loop = asyncio.get_running_loop()
print(loop)
# no need to create ClientSession for all send_req, you need only one ClientSession
async with ClientSession() as session:
# asyncio gather creates tasks itself, no need to create tasks outside
await asyncio.gather(*[send_req(session) for _ in range(8)])
if __name__ == '__main__':
# set another loop implementation:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())