我终于明白了!
首先,定义一个函数来调用另一个具有有限超时的函数:import multiprocessing
def call_timeout(timeout, func, args=(), kwargs={}):
if type(timeout) not in [int, float] or timeout <= 0.0:
print("Invalid timeout!")
elif not callable(func):
print("{} is not callable!".format(type(func)))
else:
p = multiprocessing.Process(target=func, args=args, kwargs=kwargs)
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
return False
else:
return True
函数的作用是什么?在检查超时和函数是否有效
在新进程中启动给定函数,这比线程有一些优势
阻止程序x秒(p.join())并允许在此时执行函数
超时过期后,检查函数是否仍在运行Yes:终止它并返回False
不:很好,没有暂停!返回True
我们可以用time.sleep()进行测试:
^{pr2}$
我们运行一个需要1秒才能完成的函数,超时设置为2秒:No timeout
<