Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3.8 RuntimeError: no running event loop

I have taken the below code snippet from a book by author caleb hattingh. I tried running the code snippet and faced this error.(Practicing)

How do I resolve this?

import asyncio

async def f(delay):
    await asyncio.sleep(1 / delay)
    return delay

loop = asyncio.get_event_loop()
for i in range(10):
    loop.create_task(f(i))

print(loop)
pending = asyncio.all_tasks()
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()
like image 283
mikey Avatar asked Feb 15 '26 04:02

mikey


1 Answers

You have to pass the loop as argument to the .all_tasks() function:

pending = asyncio.all_tasks(loop)

Output:

<_UnixSelectorEventLoop running=False closed=False debug=False>
<_GatheringFuture pending>
Results: [8, 5, 2, 9, 6, 3, ZeroDivisionError('division by zero'), 7, 4, 1]

So for a full correction of your script:

import asyncio

async def f(delay):
    if delay:
        await asyncio.sleep(1 / delay)
    return delay

loop = asyncio.get_event_loop()
for i in range(10):
    loop.create_task(f(i))

print(loop)
pending = asyncio.all_tasks(loop)
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()
like image 130
Sy Ker Avatar answered Feb 16 '26 17:02

Sy Ker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!