FTP downloading freezes the whole application

╄→尐↘猪︶ㄣ 提交于 2019-12-07 19:01:23

问题


I'm trying to download a file from FTP server which is about 100 MB. It's a test .bin file because I'm testing the app and I guess the files I will want to download in the future will weight even more. When I want to download the file the whole application just freezes and then after a few seconds it downloads the file. The file is complete and it downloads it successfully without any errors or something like that. The only problem is the freeze.

My code:

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()

I tried using sleep() between some lines of the code e.g between the logging in and downloading the file but it didn't help and it also seems that sleep() does not work AT ALL when working with FTP.


回答1:


Download the file on another thread:

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")

Based on:
How to download a file over HTTP with multi-thread (asynchronous download) using Python 2.7

Your followup question about modifying the code for PyQt:
FTP download with text label showing the current status of the download



来源:https://stackoverflow.com/questions/57599698/ftp-downloading-freezes-the-whole-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!