0

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.

Justin
  • 2,322
  • 1
  • 16
  • 22
  • Yeah, I think that does. Not the answer I was hoping for, but there do seem to be other options I could use. Thanks. – Justin Apr 24 '20 at 20:53
  • You almost certainly want to start the beginner's script in another process. Then you can just `os.kill()` it if takes too long. That's fairly straightforward to implement and works like a charm. – user4815162342 Apr 25 '20 at 07:47
  • The challenge is that I want to be able to kill it at the unit test level. So, for example, deleting form a linked list might work in all instances except where it is deleting the last element. I want the student to see the results of all the unit tests tests which passed while not hanging forever on the the single test that failed. So I need to run each unit test as its own process that can be killed. But that is proving to be more difficult than I had anticipated. For example, ProcessPoolExecutor does let you actually access the individual processes to be able to terminate them. – Justin Apr 29 '20 at 21:59

0 Answers0