在 Windows 上使 Python 函数超时的最简单方法

Simplest way to timeout a Python function on Windows

以下过程运行十秒钟。五秒后我想杀了它

import time

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

hello()

解决方案可能涉及线程、多处理或装饰器。之前已经问过类似的问题(提前抱歉),但解决方案都非常复杂。只需几行代码就可以实现这种听起来很基本的东西。

取决于用例...对于这个非常具体的示例

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()

是您可以做到的一种方式

或者你可以使用多处理

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