python - FTP 下载卡住整个应用程序

标签 python python-3.x ftp ftplib

我正在尝试从 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/

相关文章:

python - [sys.argv[0]] 在 python 中的含义

python - 如何将列表中名称相似的元素分组为 python 中的元组?

python - 我想对 int() 进行输入验证,但对 str() 进行输入验证

javascript - node.js 错误 : read ECONNRESET

linux - 使用 Ant 比较远程文件与本地文件的时间戳

java - 使用 Groovy 来 FTP 最新文件

python - 为什么 Django 1.0.x 无法从 PyPI 安装?

python - 使用实时视频源中的 openCV 检测球的颜色

python - 误差条图的 Matplotlib set_data

python-3.x - 以下这些作业有什么区别?