【问题标题】:Creating a timeout function in Python with multiprocessing在 Python 中使用多处理创建超时函数
【发布时间】:2016-09-03 01:27:24
【问题描述】:

我正在尝试使用多处理库在 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() 不是一个实际的函数。只是我做的其他工作的填充物。该工作不是并行完成的,也不使用任何共享变量。我只是想运行一个函数并让它可能超时。

【问题讨论】:

  • doSomeWork 是什么?
  • 只是一些填充功能。我实际的 solveProblem() 看起来不像那样。只是想简化我的问题,因为函数的内容工作正常。

标签: python timeout multiprocessing eof


【解决方案1】:

您可以为此使用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,处理了极端情况并使用了更强大的机制。然而,这或多或少是它在幕后所做的。

【讨论】:

  • 非常整洁!不幸的是,这是一个任务,所以我宁愿避免使用外部库。但对于其他项目,我会明确地记住这一点。谢谢!
【解决方案2】:

问题似乎是函数solveProblem 是在我的外部函数中定义的。 Python似乎不喜欢那样。一旦我把它移到外面,它就可以正常工作了。

当我实施 pebble 解决方案时,我会将 noxdafox 答案标记为答案。

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多