这里有一个修饰符,您可以用它来包装函数来添加超时。在
它可以在windows和linux/macos上运行。在from multiprocessing import Process, Pipe
import sys, os
class TimeoutError(Exception): pass
def spawn(f): # A decorator that calls a function given a pipe and returns the return value through it.
def func(pipe, args, kwargs, stdout, stdin):
sys.stdout = stdout
sys.stdin = stdin
pipe.send(f(*args, **kwargs)) #Pass the return arguments through the pipe
pipe.close() # Close the pipe
return func
def timeout(time):
def decorator(func):
def run_timeout(*args, **kwargs):
pipe_1, pipe_2 = Pipe()
stdin = os.fdopen(os.dup(sys.stdin.fileno()))
p = Process(target=spawn(func), args=(pipe_2, args, kwargs, sys.stdout, stdin))
p.start() # Start the function
p.join(time) # Join it back to the main process, max time seconds
if p.is_alive(): # If it timed out
p.terminate() # Kill the process
raise TimeoutError("Function %s timed out. (Took %s seconds)"%(repr(func), time)) # raise the error
return pipe_1.recv() # return the return value
return run_timeout
return decorator
像这样用
^{pr2}$
如果函数不返回,它将引发一个TimeoutError
编辑:修复了stdin可以在第二个进程中使用。在