Table of Contents
正文
1. 如何获取当前任务
2. 如何获取所有任务
Home Backend Development Python Tutorial How to get the current and running tasks in Python asynchronously

How to get the current and running tasks in Python asynchronously

May 12, 2023 pm 02:43 PM
python

正文

我们可以反省在 asyncio 事件循环中运行的任务。这可以通过为当前运行的任务和所有正在运行的任务获取一个 asyncio.Task 对象来实现。

1. 如何获取当前任务

我们可以通过 asyncio.current_task() 函数获取当前任务。此函数将为当前正在运行的任务返回一个任务对象。

...
# get the current task
task = asyncio.current_task()
Copy after login
  • 传递给 asyncio.run() 的主协程。

  • 通过 asyncio.create_task() 在 asyncio 程序中创建和调度的任务。

一个任务可以创建并运行另一个协程(例如,不包含在任务中)。从协程中获取当前任务将为正在运行的任务返回一个 Task 对象,但不会返回当前正在运行的协程。

如果协程或任务需要有关自身的详细信息,例如用于日志记录的任务名称,则获取当前任务会很有帮助。

我们可以探索如何为用于启动 asyncio 程序的主协程获取 Task 实例。下面的示例定义了一个用作程序入口点的协程。它报告一条消息,然后获取当前任务并报告其详细信息。

这是第一个重要的示例,因为它强调所有协程都可以作为异步事件循环中的任务进行访问。

下面列出了完整的示例。

# SuperFastPython.com
# example of getting the current task from the main coroutine
import asyncio
# define a main coroutine
async def main():
    # report a message
    print('main coroutine started')
    # get the current task
    task = asyncio.current_task()
    # report its details
    print(task)
# start the asyncio program
asyncio.run(main())
Copy after login

运行该示例首先创建主协程并使用它来启动 asyncio 程序。main() 协程运行并首先报告一条消息。

然后它检索当前任务,这是一个代表自身的任务对象,即当前正在运行的协程。然后它会报告当前正在运行的任务的详细信息。

我们可以看到该任务具有第一个任务的默认名称“Task-1”,并且正在执行 main() 协程,即当前正在运行的协程。

这突出表明我们可以使用 asyncio.current_task() 函数来访问当前正在运行的协程的任务对象,该对象自动包装在任务对象中。

main coroutine started
<Task pending name=&#39;Task-1&#39; coro=<main() running at ...> cb=[_run_until_complete_cb() at ...]>
Copy after login

2. 如何获取所有任务

我们可能需要访问异步程序中的所有任务。这可能有很多原因,例如:

  • 反省程序的当前状态或复杂性。

  • 记录所有正在运行的任务的详细信息。

  • 查找可以查询或取消的任务。

我们可以通过 asyncio.all_tasks() 函数在 asyncio 程序中获取一组所有已计划和正在运行(尚未完成)的任务。

...
# get all tasks
tasks = asyncio.all_tasks()
Copy after login

这将返回 asyncio 程序中所有任务的集合。它是一个集合,因此每个任务只代表一次。

如果出现以下情况,将包括一项任务:

  • 任务已安排但尚未运行。

  • 该任务当前正在运行(例如,但当前已暂停)

该集合还将包括当前正在运行的任务的任务,例如正在执行调用 asyncio.all_tasks() 函数的协程的任务。

另外,回想一下用于启动 asyncio 程序的 asyncio.run() 方法会将提供的协程包装在任务中。这意味着所有任务的集合将包括程序入口点的任务。

我们可以探索在一个 asyncio 程序中有很多任务的情况,然后得到一组所有任务。

在此示例中,我们首先创建 10 个任务,每个任务包装并运行相同的协程。主协程然后获取程序中计划或运行的所有任务的集合并报告它们的详细信息。

下面列出了完整的示例。

# SuperFastPython.com
# example of starting many tasks and getting access to all tasks
import asyncio
# coroutine for a task
async def task_coroutine(value):
    # report a message
    print(f&#39;task {value} is running&#39;)
    # block for a moment
    await asyncio.sleep(1)
# define a main coroutine
async def main():
    # report a message
    print(&#39;main coroutine started&#39;)
    # start many tasks
    started_tasks = [asyncio.create_task(task_coroutine(i)) for i in range(10)]
    # allow some of the tasks time to start
    await asyncio.sleep(0.1)
    # get all tasks
    tasks = asyncio.all_tasks()
    # report all tasks
    for task in tasks:
        print(f&#39;&gt; {task.get_name()}, {task.get_coro()}&#39;)
    # wait for all tasks to complete
    for task in started_tasks:
        await task
# start the asyncio program
asyncio.run(main())
Copy after login

运行该示例首先创建主协程并使用它来启动 asyncio 程序。main() 协程运行并首先报告一条消息。然后它创建并安排 10 个包装自定义协程的任务。然后 main() 协程会阻塞片刻以允许任务开始运行。任务开始运行,每个任务报告一条消息,然后休眠。

main() 协程恢复并获取程序中所有任务的列表。然后它报告每个的名称和协程。最后,它枚举已创建的任务列表并等待每个任务完成。

这突出表明我们可以获得 asyncio 程序中所有任务的集合,其中包括创建的任务以及代表程序入口点的任务。

main coroutine started
task 0 is running
task 1 is running
task 2 is running
task 3 is running
task 4 is running
task 5 is running
task 6 is running
task 7 is running
task 8 is running
task 9 is running
> Task-9,
> Task-2,
> Task-11,
> Task-7,
> Task-4,
> Task-10,
> Task-8,
> Task-5,
> Task-1,
> Task-3,
> Task-6,

接下来,我们将探讨如何同时运行多个协程。

The above is the detailed content of How to get the current and running tasks in Python asynchronously. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles