2011-03-17 43 views
1

我有一個多處理代碼,用於在特定情況下搜索數據庫記錄,當它到達數據庫的末尾時,循環必須停止,我該怎麼做?這裏是代碼:如何退出Python多重處理循環?

import psycopg2 
from multiprocessing import Pool 

conn = psycopg2.connect(a database) 
query=conn.cursor() 
query.execute(some query) 

def scanfile(): 
    try: row=query.fetchone() 
    except: return False #here the loop must stop 
    #do something with row... 

if __name__=='__main__': 
    pool=Pool() 
    while True: 
     pool.apply_async(scanfile) 
    pool.close() 
    pool.join() 
+1

這聽起來像個壞主意。檢查http://initd.org/psycopg/docs/usage.html#thread-and-process-safety – 2011-03-17 19:43:16

+0

到目前爲止,它工作,它抓住行,並與它做事,但程序永遠不會完成。 – Pablo 2011-03-17 19:46:38

回答

1

將您的查詢/光標移動爲可迭代,讓多處理爲您分配工作。

import psycopg2 
from multiprocessing import Pool 


def scanfile(row): 
    #do something with row... 


if __name__ == '__main__': 
    conn = psycopg2.connect(a database) 
    query = conn.cursor() 
    query.execute(some query) 
    pool = Pool() 
    pool.map_async(scanfile, query).wait() 
    pool.close() 
    pool.join() 
+0

非常好,它也解決了光標問題。 – Pablo 2011-03-17 21:56:34