petelin
2017-08-15 14:43:00 +08:00
```
def run_with_limited_time(func, args, kwargs, time):
"""Runs a function with time limit
:param func: The function to run
:param args: The functions args, given as tuple
:param kwargs: The functions keywords, given as dict
:param time: The time limit in seconds
:return: True if the function ended successfully. False if it was terminated.
"""
def wrapper(queue, func, *args, **kwargs):
return queue.put(func(*args, **kwargs))
import multiprocessing
q = multiprocessing.Queue(maxsize=1)
func = functools.partial(wrapper, q, func)
p = Process(target=func, args=args, kwargs=kwargs)
p.start()
p.join(time)
if p.is_alive():
p.terminate()
raise TimeoutError('time out!')
return q.get_nowait()
```
看起来是最好的实现了