2011-08-25 46 views
11

我想了解python中的多處理。將函數的返回值賦給一個變量,用多處理?還有一個關於IDLE的問題?

from multiprocessing import Process 

def multiply(a,b): 
    print(a*b) 
    return a*b 

if __name__ == '__main__': 
    p = Process(target= multiply, args= (5,4)) 
    p.start() 
    p.join() 
    print("ok.") 

在此代碼塊中,例如,如果有變量稱爲「結果」。我們怎樣才能把乘法函數的返回值賦值給「result」?

還有一個關於IDLE的問題:當我試圖用Python Shell運行這個示例時,它不能正常工作?如果我雙擊.py文件,輸出是這樣的:

20 
ok. 

但如果我嘗試在IDLE運行此:

ok. 

謝謝...

+0

的空閒部分是一個獨立的問題(可能是IDLE所做的/必須做的標準輸出重定向導致的,這可能很難處理你的代碼)。 – delnan

回答

13

好吧,我總算這個。我期待着python文檔,並且我瞭解到:使用Queue類,我們可以從函數獲取返回值。我的代碼的最終版本是這樣的:

from multiprocessing import Process, Queue 

def multiply(a,b,que): #add a argument to function for assigning a queue 
    que.put(a*b) #we're putting return value into queue 

if __name__ == '__main__': 
    queue1 = Queue() #create a queue object 
    p = Process(target= multiply, args= (5,4,queue1)) #we're setting 3rd argument to queue1 
    p.start() 
    print(queue1.get()) #and we're getting return value: 20 
    p.join() 
    print("ok.") 

而且還有一個pipe()函數,我想我們也可以使用管道函數。但現在,隊列爲我工作。

5

這有幫助嗎?這需要的功能(及其參數)的列表,它們運行在平行, 並返回其輸出:(這是老了。這非常新版本是https://github.com/cpbl/cpblUtilities/blob/master/parallel.py

def runFunctionsInParallel(listOf_FuncAndArgLists): 
    """ 
    Take a list of lists like [function, arg1, arg2, ...]. Run those functions in parallel, wait for them all to finish, and return the list of their return values, in order. 

(This still needs error handling ie to ensure everything returned okay.) 

    """ 
    from multiprocessing import Process, Queue 

    def storeOutputFFF(fff,theArgs,que): #add a argument to function for assigning a queue 
     print 'MULTIPROCESSING: Launching %s in parallel '%fff.func_name 
     que.put(fff(*theArgs)) #we're putting return value into queue 

    queues=[Queue() for fff in listOf_FuncAndArgLists] #create a queue object for each function 
    jobs = [Process(target=storeOutputFFF,args=[funcArgs[0],funcArgs[1:],queues[iii]]) for iii,funcArgs in enumerate(listOf_FuncAndArgLists)] 
    for job in jobs: job.start() # Launch them all 
    for job in jobs: job.join() # Wait for them all to finish 
    # And now, collect all the outputs: 
    return([queue.get() for queue in queues]) 
+0

偉大的建議,我用它在這裏的視頻處理:http://stackoverflow.com/questions/38203239/multiprocessing-of-video-frames-in-python。但是,這隻適用於我,而無需在提供隊列之前加入進程 - 也在文檔中提到:https://docs.python.org/2/library/multiprocessing.html#programming-guidelines – jlarsch

相關問題