Search code examples
pythonpython-multiprocessingpython-multithreadingpython-decorators

Simplest way to timeout a Python function on Windows


The following process runs for ten seconds. I want to kill it after five seconds.

import time

def hello():
    for _ in range(10):
        print("hello")
        time.sleep(1)

hello()

The solution could involve threads, multiprocessing or decorators. Similar questions have been asked before (sorry in advance), but the solutions have all been highly complex. Something as basic-sounding as this should be achievable with just a few lines of code.


Solution

  • depends on use case ... for this very specific example

    import time
    
    def hello(timeout=5):
        start_time = time.time()
        for _ in range(10):
            if time.time()-start_time > timeout:
               break
            print("hello")
            time.sleep(1)
    
    hello()
    

    is one way you could do it

    alternatively you could use multiprocessing

    import multiprocessing
    ...
    if __name__ == "__main__":
      proc = multiprocessing.Process(target=hello)
      proc.start()
      time.sleep(5)
      proc.terminate()