2013-06-21 25 views
1

我有一個連接到遠程FTP服務器並下載文件的Python腳本。由於我連接的服務器是非常可靠的而不是,它經常發生傳輸延遲和傳輸速率變得非常低。但是,沒有錯誤發生,所以我的腳本也停止。如何在指定時間後中止並重試ftp下載?

我使用ftplib模塊和retrbinary函數。我希望能夠設置超時值,之後下載中止,然後自動重試/重新啓動傳輸(恢復會很好,但這不是必須的,因爲這些文件只有〜300M)。

回答

1

我管理什麼,我需要使用threading模塊做:

conn = FTP(hostname, timeout=60.) 
conn.set_pasv(True) 
conn.login() 
while True: 
    localfile = open(local_filename, "wb") 
    try: 
     dlthread = threading.Thread(target=conn.retrbinary, 
       args=("RETR {0}".format(remote_filename), localfile.write)) 
     dlthread.start() 
     dlthread.join(timeout=60.) 
     if not dlthread.is_alive(): 
      break 
     del dlthread 
     print("download didn't complete within {timeout}s. " 
       "waiting for 10s ...".format(timeout=60)) 
     time.sleep(10) 
     print("restarting thread") 
    except KeyboardInterrupt: 
     raise 
    except: 
     pass 
    localfile.close()