2012-10-02 100 views
1

我們不斷從我們的數據庫生成數據文件,然後FTP'D到不同的位置。我們有一個poler,因爲它認爲它的文件FTP是他們python ftp文件線程或多進程

目前這個過程是連續的,當這些文件得到廣大有導致顯著延遲一個備份汽車無監控此文件夾,並儘快。我想並行處理事件,即一次FTP多個文件。我不確定線程​​/多處理,以及這對我如何工作。

這裏是我的代碼

import ftplib 
ftp = ftplib.FTP('domainname.com') 
ftp.login("username","password") 
infiles = [file1,file2,file3.....filen] 
for x in infiles: 
    f = open(x,'rb') 
    ftp.storbinary('STOR %s' %x, f) 
    f.close() 
ftp.quit() 

我的想法,因爲這是I/O密集的多處理是要走的路,對如何進行任何想法。

回答

4

您可能會發現multiprocessing.Pool作爲一個高級接口非常有用。

from multiprocessing import Pool 
def upload(file): 
    ftp = ftplib.FTP('domainname.com') 
    ftp.login("username","password") 
    f = open(x,'rb') 
    ftp.storbinary('STOR %s' %x, f) 
    f.close() 
    ftp.quit() 


infiles = [file1,file2,file3.....filen] 

pool = Pool(10) # submit 10 at once 
pool.map(upload,infiles) 

這很好,因爲map的行爲就像內建函數。對於調試,只需更換pool.map - >map

+0

如果是I/O綁定,那麼你可以使用'multiprocessing.pool.ThreadPool'代替(接口是相同的,唯一的改變是導入)。 – jfs

0

把耗時的任務時爲功能

from multiprocessing import Process 

def upload_file(filename): 
    ftp = ftplib.FTP('domainname.com') 
    ftp.login("username","password") 
    f = open(x,'rb') 
    ftp.storbinary('STOR %s' %x, f) 
    f.close() 
    ftp.quit() 

def multi_ftp(): 
    files = [file1, file2, ...] 
    processes = [] 
    for filename in files: 
     p = Process(target=filename, args=(filename,)) 
     p.start() 
     processes.append(p) 

    for p in processes: 
     p.join() 
1

我不手邊有一個代碼片段,但對於生產環境中我會definitivly看Twisted。 Twisted並不是最容易入門的工具,但它帶來了很多你以後會自己實現的東西。所以我會建議花費至少幾個小時檢查一下。