简体   繁体   English

python中如何实现async方法

[英]How to implement async method in python

I want to implement async method in the following code:我想在下面的代码中实现异步方法:

import time

def main(num):
    num_list = []
    for i in range(num):
        num_list.append(i)
        print("The number that is added in list is:", i)
        time.sleep(2)
    return num_list


def count():
    start_time = time.time()
    num_list = [3,5,2,8,2]
    for i in num_list:
        print("\nIn count() = ", i)
        data = main(i)
        print("Got data from main() = ", data)
        time.sleep(2)
    total_time = time.time() - start_time
    print("The code took",total_time,"seconds to complete")

if __name__ == "__main__":
    count()

This code takes 50s to complete.此代码需要 50 秒才能完成。 I tried to implement async method in this code but I was not able to succeed because I just started learning about it.我试图在此代码中实现异步方法,但未能成功,因为我才刚刚开始学习它。 Can you tell me how can I implement async method in this code.你能告诉我如何在这段代码中实现异步方法吗?

Here's the code where I tried to implement async method:这是我尝试实现异步方法的代码:

import asyncio, time
from asgiref.sync import sync_to_async

@sync_to_async
def main(num):
    num_list = []
    for i in range(num):
        num_list.append(i)
        print("The number that is added in list is:", i)
        time.sleep(2)
    return num_list

def get_data(data_var):
    try:
        data_var.send(None)
    except StopIteration as e:
        return e.value


async def count():
    start_time = time.time()
    num_list = [3,5,2,8,2]
    for i in num_list:
        print("In count() :".format(i))
        task1 = asyncio.ensure_future(main(i))
        data = get_data(main(i))
        print("In main() = {}".format(data))
        await asyncio.sleep(2)
        await task1
    total_time = time.time() - start_time
    print("The code took",total_time, "seconds to complete")

if __name__ == "__main__":
    asyncio.run(count())

And I am not getting num_list as return value instead I am getting None.我没有得到 num_list 作为返回值,而是得到了 None。

If you can convert your main into async function, then it can be written as this.如果你能把你的main转成async function,那么就可以这样写了。

import asyncio
import time
from loguru import logger


async def main(num):
    num_list = []
    for i in range(num):
        num_list.append(i)
        logger.info(f"The number that is added in list is: {i}")
        await asyncio.sleep(2)
    return num_list


async def count():
    start_time = time.time()
    num_list = [3,5,2,8,2]
    task_list = []
    for i in num_list:
        logger.info(f"In count() = {i}")
        task = asyncio.create_task(main(i))
        task_list.append(task)
    result_list = await asyncio.gather(*task_list)
    for r in result_list:
        logger.info(f"Got data from main() = {r}")
    total_time = time.time() - start_time
    logger.info(f"The code took {total_time} seconds to complete")

loop = asyncio.get_event_loop()
loop.run_until_complete(count())

If you can't convert the main function, threading is your best bet.如果你不能转换主要的 function,线程是你最好的选择。

from concurrent.futures import ThreadPoolExecutor, as_completed
from loguru import logger

def main(num):
    num_list = []
    for i in range(num):
        num_list.append(i)
        logger.info(f"The number that is added in list is: {i}")
        time.sleep(2)
    return num_list


def count():
    start_time = time.time()
    num_list = [3,5,2,8,2]
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = {}
        for k in num_list:
            logger.info(f"In count() = {k}")
            futures[executor.submit(main, k)] = k
        for future in as_completed(futures):
            logger.info(f"Got data from main() = {future.result()}")
            time.sleep(2)
        total_time = time.time() - start_time
        logger.info(f"The code took {total_time} seconds to complete")

count()

Both will achieve the same goal in terms of overall execution time.两者都将在整体执行时间方面实现相同的目标。

That is really not the way to do asynchronous programming, check out this article那真的不是做异步编程的方法,看看这篇文章

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM