在等待下一个ipython并行映射结果时处理异常
我想在ipython并行映射到达时迭代一些异步结果。我能找到的唯一方法是迭代results对象。但是,如果其中一个任务引发异常,迭代将终止。有没有办法做到这一点?参见下面的代码,当第二个作业引发异常时,迭代终止在等待下一个ipython并行映射结果时处理异常,ipython,ipython-parallel,Ipython,Ipython Parallel,我想在ipython并行映射到达时迭代一些异步结果。我能找到的唯一方法是迭代results对象。但是,如果其中一个任务引发异常,迭代将终止。有没有办法做到这一点?参见下面的代码,当第二个作业引发异常时,迭代终止 from IPython import parallel def throw_even(i): if i % 2 == 0: raise RuntimeError('ERROR: %d' % i) return i rc = parallel.Clie
from IPython import parallel
def throw_even(i):
if i % 2 == 0:
raise RuntimeError('ERROR: %d' % i)
return i
rc = parallel.Client()
lview = rc.load_balanced_view() # default load-balanced view
# map onto the engines.
args = range(1, 5)
print args
async_results = lview.map_async(throw_even, range(1, 5), ordered=True)
# get results
args_iter = iter(args)
results_iter = iter(async_results)
while True:
try:
arg = args_iter.next()
result = results_iter.next()
print 'Job %s completed: %d' % (arg, result)
except StopIteration:
print 'Finished iteration'
break
except Exception as e:
print '%s: Job %d: %s' % (type(e), arg, e)
给出在报告作业3和4之前停止的以下输出
[1, 2, 3, 4]
Job 1 completed: 1
<class 'IPython.parallel.error.RemoteError'>: Job 2: RuntimeError(ERROR: 2)
Finished iteration
[1,2,3,4]
完成作业1:1
:作业2:运行时错误(错误:2)
完成迭代
有什么方法可以做到这一点吗?这可能是相关的。不过,我真的不明白为什么要从远程引擎抛出异常。不过,如果你真的想这样做,我想你可以用我回答上述问题的方法来做。我现在看到你已经在你的评论中意识到了这一点,但无论如何,这应该可以做到
def throw_even(i):
if i%2:
return i
raise(RuntimeError('Error %d'%i)
params = range(1,5)
n_cores = len(c.ids)
for n,p in enumerate( params ):
core = c.ids[n%n_cores]
calls.append( c[core].apply_async( throw_even, p ) )
#then you get the results
while calls != []:
for c in calls:
try:
result = c.get(1e-3)
print(result[0])
calls.remove( c )
#in the case your call failed, you can apply_async again.
# and append the call to calls.
except parallel.TimeoutError:
pass
except Exception as e:
knock_yourself_out(e)
一种隐蔽的方法是进入
AsyncMapResult
的内部,然后抓取\u result
,这是一个结果列表。这并不能直接帮助您,但只能在以下事实之后:
tt = async_results._results
fail_indx = [j for j, r in enumerate(tt) if isinstance(r, IPython.parallel.error.RemoteError)]
good_indx = [j for j, r in enumerate(tt) if not isinstance(r, IPython.parallel.error.RemoteError)]
just_the_results = [r for r in tt if not isinstance(r, IPython.parallel.error.RemoteError)]
我已经意识到地图习惯用法不是一个合适的方法。我最好只使用lview.apply并单独处理每个结果。您并不总是希望在远程引擎上引发异常,而是您的代码/数据找到了新的有趣的方法来在远程引擎上中断;)当你无法返回500多个结果时,这是非常令人恼火的,因为其中7个有扭曲的数据。当然,为每个参数创建一个不同的视图应该可以封装异常。