Skip to main content
 首页 » 编程设计

python之检查FTP连接是否成功打开,文件是否已上传到Python中的FTP

2025年01月19日13lautakyan007

我正在构建一个远程延时相机,每半小时拍照一次,然后通过 FTP 将它们发送到我的服务器。 Raspberry Pi 将控制摄像头,收集文件并通过 Python 脚本将它们发送过来,如下所示:

while true 
    captureImages() 
    renameFiles(picID)  
    upload() #uploads any files and folders in the selected path 
    delete () #deletes the uploaded files from the pi 

我的问题与此 upload 函数(工作正常)和后续的 delete 函数有关

def upload():#sends the file to server 
    print ("connecting") 
    #ftp connection (server, user,pass) 
    ftp = ftplib.FTP('server','user','pass') 
 
    #folder from which to upload 
    template_dir = '/home/pi/captures/' 
 
    print ("uploading") 
    #iterate through dirs and files  
    for root, dirs, files in os.walk(template_dir, topdown=True): 
        relative = root[len(template_dir):].lstrip(os.sep) 
       #enters dirs  
        for d in dirs: 
            ftp.mkd(os.path.join(relative, d)) 
        #uploads files 
        for f in files: 
            ftp.cwd(relative) 
            ftp.storbinary('STOR ' + f, open(os.path.join(template_dir, relative, f), 'rb')) 
            ftp.cwd('/') 

这里我需要的是两件事:

  1. 一种确认文件已成功上传的方法,例如用于触发或不触发“删除”功能的 bool 值“上传(真/假)”。

  2. 如果由于任何原因无法建立连接,跳过上传过程并且不删除文件的方法。就像超时一样,一个 10 秒的窗口会尝试建立连接,如果不能,它会跳过“上传”和“删除”,因此将文件存储在本地,并在 while 循环的下一次迭代中重试。

预先感谢您的帮助!

请您参考如下方法:

代码会抛出错误。因此,如果连接失败,上传将不会发生。同样,如果 upload 失败,则不会调用 delete。

你所要做的就是在你的无限循环中捕获任何异常,这样它就不会中断:

while true 
    try: 
        captureImages() 
        renameFiles(picID)  
        upload() #uploads any files and folders in the selected path 
        delete () #deletes the uploaded files from the pi 
    except: 
        print("Error:", sys.exc_info()[0]) 

了解 Handling exceptions in Python .