我正在尝试从 FTP 服务器下载一个大约 100 MB 的文件。这是一个测试 .bin 文件,因为我正在测试该应用程序,我猜我将来想要下载的文件会更重。当我想下载文件时,整个应用程序就会卡住,几秒钟后它就会下载文件。该文件已完成,并且已成功下载,没有任何错误或类似的情况。唯一的问题是卡住。
我的代码:
ftp = FTP('exampledomain.com')
ftp.login(user='user', passwd='password')
ftp.cwd('/main_directory/')
filename = '100MB.bin'
with open(filename, 'wb') as localfile:
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
ftp.quit()
localfile.close()
我尝试在代码的某些行之间使用 sleep()
,例如在登录和下载文件之间,但它没有帮助,而且似乎 sleep()
code> 在使用 FTP 时根本不起作用。
最佳答案
在另一个线程上下载文件:
import threading
import time
from ftplib import FTP
def download():
ftp = FTP('exampledomain.com')
ftp.login(user='user', passwd='password')
ftp.cwd('/main_directory/')
filename = '100MB.bin'
with open(filename, 'wb') as localfile:
ftp.retrbinary('RETR ' + filename, localfile.write)
ftp.quit()
print("Starting download...")
thread = threading.Thread(target=download)
thread.start()
print("Download started")
while thread.isAlive():
print("Still downloading...")
time.sleep(1)
print("Done")
基于:
How to download a file over HTTP with multi-thread (asynchronous download) using Python 2.7
关于修改 PyQt 代码的后续问题:
FTP download with text label showing the current status of the download
关于python - FTP 下载卡住整个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599698/