在Windows上让Python函数超时的最简单方法是使用concurrent.futures
模块中的ThreadPoolExecutor
类。这个类允许你设置一个超时时间,当函数执行超过这个时间时,会抛出一个TimeoutError
异常。
以下是一个简单的示例代码:
import concurrent.futures
import time
def my_function():
time.sleep(5) # 模拟一个耗时操作
return "Function completed"
def run_with_timeout(func, timeout):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(func)
try:
result = future.result(timeout=timeout)
print(result)
except concurrent.futures.TimeoutError:
print("Function timed out")
if __name__ == "__main__":
run_with_timeout(my_function, timeout=3)
timeout
参数即可实现超时控制。通过上述方法,可以在Windows上简单有效地实现Python函数的超时控制。
领取专属 10元无门槛券
手把手带您无忧上云