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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With