我正在使用 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 连接会挂起,我该如何监控?因此,如果发生这种情况,我想以某种方式终止线程并启动一个新线程。
谢谢