线程和多处理的眼睛糖果。
Pebble的Python项目详细描述
pebble提供了一个整洁的api来管理应用程序中的线程和进程。
Source: | https://github.com/noxdafox/pebble |
---|---|
Documentation: | https://pebble.readthedocs.io |
Download: | https://pypi.python.org/pypi/pebble |
示例
在单独的线程中运行作业并等待其结果。
frompebbleimportconcurrent@concurrent.threaddeffunction(foo,bar=0):returnfoo+barfuture=function(1,bar=2)result=future.result()# blocks until results are ready
运行一个超时10秒的函数并处理错误。
frompebbleimportconcurrentfromconcurrent.futuresimportTimeoutError@concurrent.process(timeout=10)deffunction(foo,bar=0):returnfoo+barfuture=function(1,bar=2)try:result=future.result()# blocks until results are readyexceptTimeoutErroraserror:print("Function took longer than %d seconds"%error.args[1])exceptExceptionaserror:print("Function raised %s"%error)print(error.traceback)# traceback of the function
池支持工人重新启动、长时间运行的任务超时等等。
frompebbleimportProcessPoolfromconcurrent.futuresimportTimeoutErrordeffunction(foo,bar=0):returnfoo+bardeftask_done(future):try:result=future.result()# blocks until results are readyexceptTimeoutErroraserror:print("Function took longer than %d seconds"%error.args[1])exceptExceptionaserror:print("Function raised %s"%error)print(error.traceback)# traceback of the functionwithProcessPool(max_workers=5,max_tasks=10)aspool:foriinrange(0,10):future=pool.schedule(function,args=[i],timeout=3)future.add_done_callback(task_done)