【发布时间】:2018-04-02 23:29:31
【问题描述】:
我正在构建一个远程延时相机,它每半小时拍照一次,并通过 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('/')
我需要的是两件事:
一种确认文件是否已成功上传的方法,例如 bool 'uploaded(true/false)' 来触发或不触发 'remove' 功能。
如果由于某种原因无法建立连接,则可以跳过上传过程而不删除文件。就像超时一样,它会在 10 秒的窗口中尝试建立连接,如果无法建立连接,它会跳过“上传”和“删除”,因此将文件存储在本地并在下一次 while 循环迭代时重试。
提前感谢您的帮助!
【问题讨论】:
-
代码会报错。因此,如果
upload失败,则不会调用delete。 -
问题在于相机会停止拍照,因为在这种情况下循环会中断,对吧?
-
所以在循环中捕获异常。
-
对不起,我不知道该怎么做。这就是我在问题中提出的问题。你有什么建议吗?
标签: python python-3.x error-handling ftp ftplib