【问题标题】:How to call an async function during debugging?如何在调试期间调用异步函数?
【发布时间】:2023-02-04 10:39:01
【问题描述】:

我通常喜欢在控制台调试期间调用一些函数,只是为了快速查看一些结果。 但是对于异步函数,这似乎是不可能的:

import asyncio

async def func1():
    print('func1')

def func2():
    print('func2')

async def main():
    task = asyncio.create_task(func1())
    await task  # put a break point here

asyncio.run(main())

假设我们在await task 行中放置了一个断点 现在,如果我在控制台中调用func2(),它将完美打印'func2'。 但是,如果我在控制台输入await task,我会得到以下错误:

  File ".../anaconda3/lib/python3.9/asyncio/base_events.py", line 585, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running

蟒蛇3.9 pycharm 2022.3.1

有什么办法可以像调用非异步函数一样在控制台中调用异步函数吗?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    您可以暂停 current_task,然后运行事件循环,直到 task 完成。

    import asyncio
    from asyncio import tasks
    
    def wait(task_or_coro):
        task = asyncio.ensure_future(task_or_coro)
        loop, current_task = task.get_loop(), tasks.current_task()
        tasks._leave_task(loop, current_task)
        while not task.done():
            loop._run_once()
        tasks._enter_task(loop, current_task)
        return task.result()
    

    呼叫wait(task)而不是await task

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 1970-01-01
      • 2018-10-03
      • 2020-12-20
      • 2017-07-10
      • 2021-10-15
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多