I would like to be able to break an infinite loop after a specified amount of time. I was hoping I could achieve this with Pythons asyncio.wait_for
.
I have the following example
import asyncio
async def infinite_loop():
i = 0
while True:
i = i + 1
async def main():
try:
await asyncio.wait_for(infinite_loop(), 1)
except:
print("Break out!")
asyncio.run(main())
I would like this to stop infinite_loop
after one second but it does not do so and I am not understanding why.
I am looking for this behavior because I am writing test scripts for beginning programmers in a class who might create functions that get into an infinite loop. I need a way to reliably break out of a test function that gets into an infinite loop while being tested in unittest
. Currently when it encounters such a function it hangs and will not run subsequent tests, even if they would have passed.