python - 使用 Python 3.6 asyncio 异步运行任务

标签 python python-3.x python-asyncio

我开始开发一个与 AWS Boto 通信的新 Python 3.6 项目。由于启动 EC2 实例需要一些时间,因此我开始使用 asyncio 库,但在理解它时遇到了一些麻烦。

我想异步启动 2 个 EC2 实例。但是,如果我调用 run_tests 我会收到以下错误:

ERROR:asyncio:Task was destroyed but it is pending!

这是我当前的代码:

from manager import Manager
import asyncio


async def run_new_vm(manager, loop, vm_name):
    new_instance = manager.launch_ec2_instance(vm_name)
    task = loop.create_task(new_instance)
    task.add_done_callback(lambda f: do_something(manager, f.result()))


def do_something(manager, instance):
    // Do stuff once the instance is usable


async def one_service_per_vm(n, manager, loop):
    for x in range (0, n):
        print('Started with number %s.' % x)
        loop.create_task(run_new_vm(manager, loop, n))


def run_tests():
    loop = asyncio.get_event_loop()
    m = Manager()
    loop.run_until_complete(one_service_per_vm(2, m, loop))
    loop.close()

我做错了什么?

最佳答案

您正在使用 create_task 在循环中安排作业,但没有任何东西等待它们完成。 one_service_per_vm 将立即返回。

您可以使用asyncio.gatherawait许多任务

# ...

async def one_service_per_vm(n, manager, loop):
    tasks = [run_new_vm(manager, loop, n) for x in range (0, n)]
    await asyncio.gather(*tasks, loop=loop)


def run_tests():
    loop = asyncio.get_event_loop()
    m = Manager()
    loop.run_until_complete(one_service_per_vm(2, m, loop))
    loop.close()

关于python - 使用 Python 3.6 asyncio 异步运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936032/

相关文章:

python - pytest-nodev : automatic permutation of arguments

python - 从 Google AppEngine 中的 blobstore 下载 zip 存档

python - 从命令行运行时出现 ModuleNotFoundError

Python3 属性错误 : 'list' object has no attribute 'clear'

python - 任何人都可以将此 rsync 命令解析为与 asyncio.subprocess 一起使用的列表吗?

python - 通过使用多进程和多线程的 asyncio 提高 "Sending 100,000 request"的速度

python - 创建列表,其中的元素是子列表,这些子列表在其他两个列表的子列表中的元素之间交替

python - 测试 Python 字符串中的 bool 表达式

python - 打包后,module1不能来自同一个项目 "import module2"

python-3.x - 使用异步和线程