【问题标题】:How to add a task to event loop while it is already running in asyncio library in python3.7?如何在 python3.7 的 asyncio 库中运行时将任务添加到事件循环?
【发布时间】: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


【解决方案1】:

我做错了什么

是的。由于 asyncio 不是线程安全的,因此您无法从运行事件循环的线程外部与事件循环进行交互。创建任务的正确方法是:

asyncio.run_coroutine_threadsafe(main(), event_loop)

另请参阅事件循环中的call_soon_threadsafe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2023-03-04
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多