在阅读了 Pebble 的文档 ( https://pythonhosted.org/Pebble/ ) 之后,它看起来很简单。尽管如此,我无法得到预期的结果。
我从他们网站上给出的一个例子开始
import time
from pebble import concurrent, ProcessExpired
from concurrent.futures import TimeoutError
@concurrent.process(timeout=10)
def function(foo, bar=0):
time.sleep(5)
return foo + bar
future = function(1, bar=2)
try:
result = future.result()
except TimeoutError as error:
print("function took longer than %d seconds" % error.args[1])
except ProcessExpired as error:
print("%s. Exit code: %d" % (error, error.exitcode))
except Exception as error:
print("function raised %s" % error)
print(error.traceback)
else:
print(str(result))
我的理解:
- 已为函数设置了 10 秒的超时
- future.result() 阻塞,直到结果准备好
- 函数执行大约需要 5 秒
- 您将直接转到try / except的else “分支”并获得打印结果,即“3”
事实上,我从来没有得到想要的结果,而是消息“函数花费了超过 10 秒”。
你能告诉我我错过了什么以获得预期的结果(即 foo + bar)吗?