2013-03-10 37 views
4

我經歷的多教程這裏:http://pymotw.com/2/multiprocessing/basics.html正確地實現的Python多重

我寫了下面的腳本練習。該腳本似乎正在工作,我看到5個新的python進程在taskmgr中運行。但是,我的打印語句輸出多次搜索相同的文件夾。

我有一個懷疑,而不是分裂不同進程之間的工作,我給每個進程的整個工作量。我很確定我做錯了,效率低下。有人能指出我的錯誤嗎?

我有什麼至今:

def email_finder(msg_id): 
    for folder in os.listdir(sample_path): 
     print "Searching through folder: ", folder 
     folder_path = sample_path + '\\' + folder 
     for file in os.listdir(os.listdir(folder_path)): 
      if file.endswith('.eml'): 
       file_path = folder_path + '\\' + file 
       email_obj = email.message_from_file(open(file_path)) 
       if msg_id in email_obj.as_string().lower() 
        shutil.copy(file_path, tmp_path + '\\' + file) 
        return 'Found: ', file_path 
    else: 
     return 'Not Found!' 

def worker(): 
    msg_ids = cur.execute("select msg_id from my_table").fetchall() 
    for i in msg_ids: 
     msg_id = i[0].encode('ascii') 
     if msg_id != '': 
      email_finder(msg_id) 
    return 

if __name__ == '__main__': 
    jobs = [] 
    for i in range(5): 
     p = multiprocessing.Process(target=worker) 
     jobs.append(p) 
     p.start() 

回答

5

你的子過程中的每一個都有自己的光標,在整個集ID的迭代爲此。

您需要從數據庫中讀取msg_ids一次,然後將其產生到子流程,而不是讓每個子流程自行查詢。

+0

啊,這很有道理:)謝謝! – 2013-03-10 17:04:44

+0

完成:)用戶界面迫使我等待一分鐘才接受。 – 2013-03-10 17:08:58