3

I usually like to call some functions during debugging in the console just to see some quick results. However with async functions, this doesn't seem to be possible:

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())

Let's say we put a break point in the line of await task Now if I call func2() in the console it will print 'func2' perfectly fine. However, if I enter await task in console, I will get the below error:

  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

python 3.9 pycharm 2022.3.1

Is there any way I can call the async functions in the console like the non-async functions?

1 Answer 1

5

You can suspend the current_task and then run the event loop until the task is done.

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()

Call wait(task) instead of await task.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Just curious is this the 'canonical' way of debugging async functions?
It depends on the scenario; this seems to be the only way to do so from a debugger (it's generally not advisable to use single-underscore functions that are "private"). For the case in the question, I wonder why you don't simply Step Over/Into?
The reason that I cannot simply step into is that I often need to call those async functions out of order during debugging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.