[英]The thread hangs using FTP LIST with Python
我正在使用ftplib從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連接掛起,我該如何監控? 因此,如果發生這種情況,我想以某種方式終止線程並啟動一個新線程。
謝謝
如果要增強魯棒性,我強烈建議您考慮使用事件驅動的方法。 具有FTP支持的一種就是Twisted ( API )。
優點是您在等待I / O時不會阻塞線程,並且可以根據需要創建簡單的計時器函數來監視連接。 它的伸縮性也更好。 使用事件驅動的模式編寫代碼稍微復雜一些,因此,如果這只是一個簡單的腳本,則可能值得或不值得付出額外的努力,但是由於您編寫的是編寫守護程序,因此值得研究。
這是FTP客戶端的示例: ftpclient.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.