简体   繁体   English

Python asyncio - 如何创建任务列表并在事件循环中使用它?

[英]Python asyncio - How to create task list and use it in the event loop?

I'm not very experienced in Python asyncio, although synchronous Python is going well.我在 Python asyncio 方面不是很有经验,尽管同步 Python 进展顺利。 I have a function, which creates a task list, and another function which is to be called with tasks in this list:我有一个函数,它创建一个任务列表,另一个函数将被这个列表中的任务调用:

import asyncio

async def createTasks(some_dict):
    coroutines = []
    # some_dict can have an arbitrary number of items
    for item in some_dict:
        coroutines.append(executeOneTask(item))
    tasks = await asyncio.gather(*coroutines, return_exceptions=True)
    return tasks

async def executeOneTask(item):
    # execute a task asynchronously
    return

Here's the part where you are free to correct me if I'm wrong.如果我错了,这是您可以自由纠正我的部分。

Now, my understanding of asyncio is that I need an event loop to execute an asynchronous function, which means that to asyncio.gather I need to await it that means this needs to happen inside an async function.现在,我对 asyncio 的理解是我需要一个事件循环来执行异步函数,这意味着对于asyncio.gather我需要await它,这意味着这需要在async函数中发生。 OK, so I need an event loop to create my list of asynchronous tasks that I actually want to execute asynchronously.好的,所以我需要一个事件循环来创建我实际上想要异步执行的异步任务列表。

If my understanding of event loops is correct, I cannot easily add tasks inside an event loop to that same event loop.如果我对事件循环的理解是正确的,我就不能轻易地将事件循环内的任务添加到同一个事件循环中。 Let's assume that I have an asynchronous main() function which is supposed to first retrieve a list of asynchronous tasks using createTasks() and then create an amount (equal to list length) of asynchronous tasks to be run by utilizing executeOneTask() .假设我有一个异步main()函数,它应该首先使用createTasks()检索异步任务列表,然后使用executeOneTask()创建要运行的异步任务数量(等于列表长度executeOneTask()

How should I approach the construction of such a main() function?我应该如何构建这样的main()函数? Do I need multiple event loops?我需要多个事件循环吗? Can I create a task list some other way, which enables easier code?我可以通过其他方式创建任务列表,从而使代码更简单吗?

Side note: The approach I have set up here might be a very difficult or upside-down way to solve the problem.旁注:我在这里设置的方法可能是解决问题的一种非常困难或颠倒的方法。 What I aim to do is to create a list of asynchronous tasks and then run those tasks asynchronously.我的目标是创建一个异步任务列表,然后异步运行这些任务。 Feel free to not follow the code structure above if a smart solution requires that.如果智能解决方案需要,请随意不遵循上面的代码结构。

Thanks!谢谢!

You should only use one event loop in the entire application.您应该在整个应用程序中只使用一个事件循环。 Start the main function by asyncio.run(main()) and asyncio creates a loop for you.通过asyncio.run(main())启动 main 函数, asyncio.run(main())为您创建一个循环。 With Python 3.8 you rarely need to access or use the loop directly but with older versions you may obtain it by asyncio.get_event_loop() if using loop methods or some functions that require loop argument.在 Python 3.8 中,您很少需要直接访问或使用循环,但在旧版本中,如果使用循环方法或某些需要循环参数的函数,您可以通过asyncio.get_event_loop()获得它。

Do note that IPython (used in Spyder and Jupyter) also runs its own loop, so in those you can directly call and await without calling asyncio.run .请注意,IPython(在 Spyder 和 Jupyter 中使用)也运行自己的循环,因此在那些循环中,您可以直接调用和await而无需调用asyncio.run

If you only wish to do async programming but don't specifically need to work with asyncio, I would recommend checking out https://trio.readthedocs.io/ which basically does the same things but is much, much easier to use (correctly).如果您只想进行异步编程但并不特别需要使用 asyncio,我建议您查看https://trio.readthedocs.io/ ,它基本上可以做同样的事情,但使用起来要容易得多(正确)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asyncio create task and aiohttp, 'no running event loop' - asyncio create task and aiohttp , 'no running event loop' 从不同的事件循环取消Python Asyncio任务 - Python Asyncio Task Cancel From Different Event Loop 如何在库函数中使用asyncio事件循环 - How to use asyncio event loop in library function Python asyncio:如何在Task.cancel之间安全地在线程之间关闭事件循环? - Python asyncio : how to close a event loop after Task.cancel safely among threads? 从 loop.create_task() 引发的 python asyncio 异常 - python asyncio exceptions raised from loop.create_task() Python 的 asyncio `loop.create_task(...)` 是线程安全的吗? - Is Python's asyncio `loop.create_task(...)` threadsafe? 如何从视图中的异步事件循环中获取任务? - How to get task out of asyncio event loop in a view? 如何使用 Uvicorn 和 asyncio.create_task() 将任务置于后台? - How to use Uvicorn with asyncio.create_task() to put task in background? asyncio/aiohttp - create_task() 阻止事件循环,在“此事件循环已在运行”中收集结果 - asyncio/aiohttp - create_task() blocks event loop, gather results in “This event loop is already running ” Python asyncio loop.create_task 和 asyncio.run_coroutine_threadsafe 的区别 - Python asyncio difference between loop.create_task and asyncio.run_coroutine_threadsafe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM