相关疑难解决方法(0)

使用队列导致asyncio异常"将Future <Future pending>附加到不同的循环"

我正在尝试使用asyncio队列运行这个简单的代码,但是捕获异常,甚至嵌套异常.

我希望得到一些帮助,使asyncio中的队列正常工作:

import asyncio, logging

logging.basicConfig(level=logging.DEBUG)
logging.getLogger("asyncio").setLevel(logging.WARNING)


num_workers = 1
in_queue = asyncio.Queue()
out_queue = asyncio.Queue()
tasks = []


async def run():
    for request in range(1):
        await in_queue.put(request)

    # each task consumes from 'input_queue' and produces to 'output_queue':
    for i in range(num_workers):
        tasks.append(asyncio.create_task(worker(name=f'worker-{i}')))
    # tasks.append(asyncio.create_task(saver()))

    print('waiting for queues...')
    await in_queue.join()
    # await out_queue.join()
    print('all queues done')

    for task in tasks:
        task.cancel()
    print('waiting until all tasks cancelled')
    await asyncio.gather(*tasks, return_exceptions=True)
    print('done')


async def worker(name):
    while True:
        try:
            print(f"{name} started")
            num = …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-asyncio

4
推荐指数
1
解决办法
3079
查看次数

标签 统计

python ×1

python-3.x ×1

python-asyncio ×1