2014-09-10 137 views
2

我想收集pool.map函數調用中的時間和失敗消息,並在所有作業完成時將其打印出來。在Python中可能嗎?是否可以在pool.map完成python作業後執行代碼?

或許有一些事件..要不然不服......

failures = [] 

def test(): 
    sleep(1) 
    global failures 
    failures.append('test message') 

def main(): 
    data = [...] 
    pool = ThreadPool(45) 
    results = pool.map(test, data) 
    pool.close() 
    pool.join() 

    # after all calls are finished i want to perform this 
    print failures 
+1

的'map'函數返回結果,所以如果你對mply返回你完成的錯誤信息,對吧? :) – Wolph 2014-09-10 20:20:29

+0

有點困惑後,nodejs ..一切似乎通過異步!將嘗試做現在這個明顯的事情。 – avasin 2014-09-10 20:22:59

回答

1

示例(請注意,您可以返回任何東西,你可以回報 [不提高]例外而不是正常的結果):

import random 
import pprint 
import multiprocessing 

def test(value): 
    if random.random() > 0.5: 
     return 'Noes, we got an error for %d!' % value 
    else: 
     return 'All is ok for %d :)' % value 

def main(): 
    data = range(10) 

    pool = multiprocessing.Pool() 
    results = pool.map(test, data) 
    pool.close() 
    pool.join() 

    pprint.pprint(results) 

if __name__ == '__main__': 
    main() 

輸出示例:

['All is ok for 0 :)', 
'Noes, we got an error for 1!', 
'Noes, we got an error for 2!', 
'Noes, we got an error for 3!', 
'All is ok for 4 :)', 
'Noes, we got an error for 5!', 
'All is ok for 6 :)', 
'Noes, we got an error for 7!', 
'All is ok for 8 :)', 
'Noes, we got an error for 9!'] 
相關問題