2017-03-05 30 views
1

我不明白爲什麼一個簡單的執行程序將無法正常工作Executor.map不處理

我有兩個模塊:main.py

import other 

a = [1, 2, 3] 
b = ['a', 'b'] 
l = ['a', 'b', 'd'] 

other.run_executor(a, b, l) 

而且other.py

from concurrent import futures 
from multiprocessing import cpu_count 


def do_stuff(a, b, c): 
    print(a, b, c) 


def run_executor(a, b, l): 
    iterat = ((a, b, c) for c in l) 
    with futures.ThreadPoolExecutor(max_workers=cpu_count() - 1) as e: 
     e.map(do_stuff, iterat) 

運行此代碼不會產生錯誤,但也不會打印任何內容。 它應該打印a,b,l [0]; a,b,l [1]; a,b,l [2] 我做錯了什麼?

回答

1

這是因爲您沒有正確使用ThreadPoolExecutor.map。這些參數不應該作爲一個迭代器傳遞但3個迭代器:

from concurrent import futures 
from itertools import repeat 
from multiprocessing import cpu_count 


def do_stuff(a, b, c): 
    print(a, b, c) 


def run_executor(a, b, l): 
    with futures.ThreadPoolExecutor(max_workers=cpu_count() - 1) as e: 
     e.map(do_stuff, repeat(a), repeat(b), c) 

此外,你應該使用if __name__ == "__main__"保護你的主腳本,以避免奇怪的行爲。如果您嘗試導入/醃製其中定義的函數,此許可證可以保護您的模塊主體免於執行。

import other 

if __name__ == "__main__": 
    a = [1, 2, 3] 
    b = ['a', 'b'] 
    l = ['a', 'b', 'd'] 

    other.run_executor(a, b, l) 
+0

謝謝,它確實有效。但。再一次,我無法將它限制在主...它必須從另一個模塊調用(沒有保護)。什麼是'怪異行爲'?正如我在其他問題中所說的那樣;我的完整程序如下所示:main.py啓動進程。然後調用參數化,然後加載或創建代理,然後發生時間迭代模塊。時間迭代在需要'do_stuff()'的地方調用running_month。最重要的是,在多次模擬中,我調用了'main.py' 100次。總之,事件的排序阻止了我在內部使用do_stuff if __name__ =='__main __' –

+1

這裏唯一的約束是你不要不想創建多個工作人員池。當您導入模塊時,所有不是函數的代碼都會立即運行。因此,如果您的代碼直接在腳本中產生,則最終可能會出現錯誤或意外行爲。你不應該多次運行腳本'main.py',而是創建一個你可以導入並處理計算的'main()'函數。創建一個函數而不是腳本允許與'if main'具有相同的安全防護。 –

+0

太好了。優秀! –