在后台运行 Python 的 asyncio 任务。

huangapple go评论44阅读模式
英文:

python run asyncio task in the background

问题

我想在后台运行异步任务,以便下面的代码循环打印出'a',并在3秒后取消任务,就像代码中所示。我尝试过使用create_task和event_loops,但都没有成功。希望能得到帮助。

# SuperFastPython.com
# 在后台运行异步协程的示例

import asyncio
import time
import uuid

async def custom_coro():
    while True:
        print('a')
        time.sleep(1)
        # await asyncio.sleep(1)

async def run_ws():
    await asyncio.wait([
        custom_coro(),
    ])

if __name__ == '__main__':
    tasks = {}
    task = asyncio.run(run_ws())
    # task = asyncio.create_task(run_ws())

    task_id = str(uuid.uuid4())
    tasks[task_id] = task

    print('b')
    time.sleep(3)

    tasks[task_id].cancel()

    # tasks = asyncio.all_tasks()
    # t = tasks.pop()
    # t.cancel()

    # asyncio.run(run_ws())
    # print('b')

希望这对你有帮助。

英文:

I want to run asynio task in the background so that below code prints out 'b' once while printing out 'a' recursively. Instead it prints 'a' forever with no 'b'.

It should cancel the task after 3 seconds like shown in the code.

I tried with create_task and event_loops with no success. Any help would be appreciated.

# SuperFastPython.com
# example of running an asyncio coroutine in the background
import asyncio
import time
import uuid


async def custom_coro():
    while True:
        print('a')
        time.sleep(1)
        # await asyncio.sleep(1)

async def run_ws():

    await asyncio.wait([
        custom_coro(),
    ])

if __name__ == '__main__':
    tasks = {}
    task = asyncio.run(run_ws())
    # task = asyncio.create_task(run_ws())

    task_id = str(uuid.uuid4())
    tasks[task_id] = task

    print('b')
    time.sleep(3)

    tasks[task_id].cancel()

    # tasks = asyncio.all_tasks()
    # t = tasks.pop()
    # t.cancel()

    # asyncio.run(run_ws())
    # print('b')

答案1

得分: 1

您无法在异步任务中与time.sleep()并行使用。您可以使用类似以下的方式:

import asyncio

async def custom_coro():
    while True:
        print('a')
        await asyncio.sleep(1)
    
task = asyncio.create_task(custom_coro())
print('b')
asyncio.gather(task)
await asyncio.sleep(3)
task.cancel()
print('done')

输出 -

b
a
a
a
done
_GatheringFuture exception was never retrieved
future: <_GatheringFuture finished exception=CancelledError()>
concurrent.futures._base.CancelledError

封装在主函数中:

import asyncio

async def main():
    async def custom_coro():
        while True:
            print('a')
            await asyncio.sleep(1)

    task = asyncio.create_task(custom_coro())
    print('b')
    asyncio.gather(task)
    await asyncio.sleep(3)
    task.cancel()
    print('done')
    
asyncio.run(main())

如果您需要更多帮助,请告诉我。

英文:

You cannot have time.sleep() in parallel with an async task. You can use something like this

import asyncio

async def custom_coro():
    while True:
        print(&#39;a&#39;)
        await asyncio.sleep(1)
    
task = asyncio.create_task(custom_coro())
print(&#39;b&#39;)
asyncio.gather(task)
await asyncio.sleep(3)
task.cancel()
print(&#39;done&#39;)

Output -

b
a
a
a
done
_GatheringFuture exception was never retrieved
future: &lt;_GatheringFuture finished exception=CancelledError()&gt;
concurrent.futures._base.CancelledError

wrapped in main function:

import asyncio

async def main():
    async def custom_coro():
        while True:
            print(&#39;a&#39;)
            await asyncio.sleep(1)

    task = asyncio.create_task(custom_coro())
    print(&#39;b&#39;)
    asyncio.gather(task)
    await asyncio.sleep(3)
    task.cancel()
    print(&#39;done&#39;)
    
asyncio.run(main())

huangapple
  • 本文由 发表于 2023年2月24日 14:28:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定