【发布时间】:2020-07-17 11:45:23
【问题描述】:
# !/usr/bin/python3
import asyncio
import aiohttp
from threading import Thread
event_loop = asyncio.get_event_loop() # getting the event_loop
Thread(target=event_loop.run_forever).start() # creating one more thread(to add and then to execute tasks when it is necessary)
async def fetch(session, url): # exm/doc code from aiohttp lib.
async with session.get(url) as response:
return await response.text()
async def main(): # exm/doc code from aiohttp lib.
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
event_loop.create_task(main()) # doesn't work when the event_loop is already running... Is it the only way to add task before running the event_loop in asyncio?
目标是在必要时添加任务。例如,主线程用于监听服务器,第二个用于响应。 P.s 这只是所有代码的一小部分/
是我做错了什么还是 asyncio 库不支持这个?
【问题讨论】:
-
没有理由使用
Threading为您的event_loop调用run_forever。此外,由于您使用的是 Python 3.7,因此运行程序的首选方法应该是asyncio.run(main())
标签: asynchronous async-await python-3.7 python-asyncio event-loop