用python的ftplib库实现ftp上文件的实时下载,但是却总是出现中断,也不抛出异常
#-*-coding:utf-8-*-
import os
import time
import socket
from ftplib import FTP
import time
# 服务器地址
FTP_SERVER = '已隐藏' #- - 对应ftpe服务器地址
USER = 'test'
PWD = '123'
FTP_PATH = '/jma/netcdf/'
local_root = 'e:' + FTP_PATH
DATE = time.strftime('%Y%m%d', time.localtime(time.time()))
month=DATE[0:6]
day=DATE[6:8]
FTP_PATH =os.path.join(FTP_PATH,month,day)
FTP_PATH =FTP_PATH.replace('\\', '/')
print FTP_PATH
def ftpconnect():#ftp连接
try:
ftp=FTP()
ftp.set_debuglevel(2)
ftp.connect(FTP_SERVER,21)
except(socket.error, socket.gaierror) as e:
print 'Error ; cannot reach "%s"' %FTP_SERVER
print 'connected to host "%s"' %FTP_SERVER
try:
ftp.login(USER, PWD)
except ftp.error_perm:
print 'error: cannot login "%s"' %USER
ftp.quit()
return False
print 'logged in as "%s"' %USER
return ftp
def downloadfile():#下载文件
ftp = ftpconnect()
print ftp.getwelcome() # 显示ftp服务器欢迎信息
li = ftp.nlst(FTP_PATH)#nlst路径下的文件名列表
print 'ftp: ', li
for eachfile in li:
print eachfile.split('_')[6]
if(eachfile.split('_')[6]!= '06001.nc'):
localpath = 'e:' + eachfile
print '-- open localpath --', localpath
bufsize = 1024
fp = open(os.path.basename(eachfile), 'wb+')
try:
ftp.retrbinary('RETR ' + eachfile, fp.write, bufsize)#执行下载
except ftp.error_perm:
print(os.path.getsize(os.path.basename(eachfile)))
ftp.quit()
fp.flush()
ftp.set_debuglevel(0) # 关闭调试
fp.close()
ftp.quit() # 退出ftp服务器
if __name__ == "__main__":
downloadfile()
代码如上所示,debug一直显示connected,但是文件大小不再发生变化