2012-10-16 36 views
0

我使用ftplib連接並從FTP服務器獲取文件列表。 我遇到的問題是連接不時掛起,我不知道爲什麼。我使用線程作爲守護進程運行python腳本。 明白我的意思:線程掛起使用FTP列表與Python

def main(): 
signal.signal(signal.SIGINT, signal_handler) 

    app.db = MySQLWrapper() 
    try: 
     app.opener = FTP_Opener() 
     mainloop = MainLoop() 

     while not app.terminate: 
      # suspend main thread until the queue terminates 
      # this lets to restart the queue automatically in case of unexpected shutdown 
      mainloop.join(10) 
      while (not app.terminate) and (not mainloop.isAlive()): 
       time.sleep(script_timeout) 
       print time.ctime(), "main: trying to restart the queue" 
       try: 
        mainloop = MainLoop() 
       except Exception: 
        time.sleep(60) 

    finally: 
     app.db.close() 
     app.db = None 
     app.opener = None 
     mainloop = None 
     try: 
      os.unlink(PIDFILE) 
     except: 
      pass 
     # give other threads time to terminate 
     time.sleep(1) 
     print time.ctime(), "main: main thread terminated" 

MainLoop語句()對FTP連接的一些功能,從服務器下載特定文件和斷開。

以下是我獲取文件的列表:

file_list = app.opener.load_list() 

以及如何FTP_Opener.load_list()函數如下:

def load_list(self): 
    attempts = 0 
    while attempts<=ftp_config.load_max_attempts: 
     attempts += 1 
     filelist = [] 
     try: 
      self._connect() 
      self._chdir() 
      # retrieve file list to 'filelist' var 
      self.FTP.retrlines('LIST', lambda s: filelist.append(s)) 

      filelist = self._filter_filelist(self._parse_filelist(filelist)) 

      return filelist 
     except Exception: 
      print sys.exc_info() 
      self._disconnect() 
      sleep(0.1) 

    print time.ctime(), "FTP Opener: can't load file list" 
    return [] 

爲什麼有時FTP連接掛起,如何監控呢?所以如果發生了,我想以某種方式終止線程並開始一個新線程。

感謝

+0

哦'load_max_attempts = 10' – KennyPowers

回答

1

如果您正在爲穩健性,我會強烈建議你考慮使用事件驅動的方法。有一個這樣的FTP支持是TwistedAPI)。

好處是,您在等待I/O時不會阻塞線程,並且您可以創建簡單的定時器函數來監視連接,如果您願意的話。它也更好地擴展。使用事件驅動模式進行編碼會稍微複雜一點,所以如果這只是一個簡單的腳本,它可能值得或者不值得花費額外的努力,但是因爲你寫道你正在編寫一個守護進程,所以值得研究。

下面是一個FTP客戶端的示例:ftpclient.py