Check that FTP connection opened successfully and files have been uploaded to FTP in Python
我正在建立一个远程延时相机,每半小时拍摄一次照片,然后通过ftp发送到我的服务器。Raspberry PI将通过类似这样的python脚本控制摄像机、收集文件并发送它们:
1 2 3 4 5 | while true captureImages() renameFiles(picID) upload() #uploads any files and folders in the selected path delete () #deletes the uploaded files from the pi |
我的问题与这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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('/') |
我需要两件事:
一种确认文件已成功上载的方法,例如bool"uploaded(true/false)"以触发或不触发"remove"功能。
如果由于任何原因无法建立连接,可以跳过上载过程而不删除文件。与超时类似,一个10秒的窗口,在该窗口中,它试图建立连接,如果无法建立连接,则跳过"上载"和"删除",因此将文件存储在本地,并在while循环的下一个迭代中重试。
提前感谢您的帮助!
代码将出错。所以,如果连接失败,上传就不会发生。同样,如果
你所要做的就是在你的无止境的循环中捕获任何异常,这样它就不会中断:
1 2 3 4 5 6 7 8 | 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]) |
了解如何在Python中处理异常。