問題描述
如何處理 ftplib 中的斷開連接?
How can I handle disconnects in ftplib?
我編寫了一個 Python 腳本,我將使用它來使用 ftplib 將非常大的文件上傳到 FTP 服務器.
I wrote a Python scrip that I will use in order to upload very big files to an FTP server using ftplib.
我的問題是:由于文件的大小,上傳可能會花費很多時間,如果互聯網在中間斷開連接然后在 1 分鐘后重新連接怎么辦?如何在腳本中處理此類問題?有什么想法嗎?
My question is: Seeing as upload will probably take a lot of time due to the file's size, what if the internet disconnects in the middle and then reconnects say after 1 minute? How can I handle such issue in the script? Any ideas?
我想到的是一個 try except 塊,它不斷檢查互聯網連接是否可用.有什么想法嗎?
What I thought about is a try except block that keeps checking if internet connection is available. Any ideas?
謝謝
推薦答案
使用 Python ftplib 上傳時處理斷開連接的簡單實現:
A simple implementation for handling of disconnects while uploading with Python ftplib:
finished = False
local_path = "/local/source/path/file.zip"
remote_path = "/remote/desti/path/file.zip"
with open(local_path, 'rb') as f:
while (not finished):
try:
if ftp is None:
print("Connecting...")
ftp = FTP(host, user, passwd)
if f.tell() > 0:
rest = ftp.size(remote_path)
print(f"Resuming transfer from {rest}...")
f.seek(rest)
else:
print("Starting from the beginning...")
rest = None
ftp.storbinary(f"STOR {remote_path}", f, rest=rest)
print("Done")
finished = True
except Exception as e:
ftp = None
sec = 5
print(f"Transfer failed: {e}, will retry in {sec} seconds...")
time.sleep(sec)
建議進行更細粒度的異常處理.
類似的下載:
超時后恢復FTP下載
這篇關于在 Python ftplib FTP 傳輸文件上傳中處理斷開連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!