gpt4 book ai didi

python - 在 Python 中使用多处理创建超时函数

转载 作者:行者123 更新时间:2023-12-01 03:58:06 24 4
gpt4 key购买 nike

我正在尝试使用多处理库在 Python 2.7.11(在 Windows 上)中创建超时函数。

我的基本目标是,如果函数超时,则返回一个值;如果函数未超时,则返回实际值。

我的方法如下:

from multiprocessing import Process, Manager

def timeoutFunction(puzzleFileName, timeLimit):
manager = Manager()
returnVal = manager.list()

# Create worker function
def solveProblem(return_val):
return_val[:] = doSomeWork(puzzleFileName) # doSomeWork() returns list

p = Process(target=solveProblem, args=[returnVal])
p.start()

p.join(timeLimit)
if p.is_alive():
p.terminate()
returnVal = ['Timeout']

return returnVal

我这样调用该函数:

if __name__ == '__main__':
print timeoutFunction('example.txt', 600)

不幸的是,这不起作用,我在 pickle.py 中收到某种 EOF 错误

有人能看出我做错了什么吗?

提前致谢,
亚历山大

编辑: doSomeWork() 不是一个实际的函数。只是我所做的其他一些工作的填充物。这项工作不是并行完成的,也不使用任何共享变量。我只是尝试运行一个函数,并且可能会超时。

最佳答案

您可以使用Pebble为此的库。

from pebble import concurrent
from concurrent.futures import TimeoutError

TIMEOUT_IN_SECONDS = 10

@concurrent.process(timeout=TIMEOUT_IN_SECONDS)
def function(foo, bar=0):
return foo + bar

future = function(1, bar=2)

try:
result = future.result() # blocks until results are ready or timeout
except TimeoutError as error:
print "Function took longer than %d seconds" % error.args[1]
result = 'timeout'

documentation有更完整的示例。

如果函数超时,库将终止该函数,因此您无需担心 IO 或 CPU 被浪费。

编辑:

如果您正在做作业,您仍然可以查看 its实现。

简短示例:

from multiprocessing import Pipe, Process

def worker(pipe, function, args, kwargs):
try:
results = function(*args, **kwargs)
except Exception as error:
results = error

pipe.send(results)

pipe = Pipe(duplex=False)
process = Process(target=worker, args=(pipe, function, args, kwargs))

if pipe.poll(timeout=5):
process.terminate()
process.join()
results = 'timeout'
else:
results = pipe.recv()

Pebble 提供了一个简洁的 API,处理极端情况并使用更强大的机制。但这或多或少就是它在幕后所做的事情。

关于python - 在 Python 中使用多处理创建超时函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37098360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com