首页 > 解决方案 > FTP下载进度条

问题描述

我想在从 FTP 服务器下载文件时看到进度条。我的代码看起来像这样,但我得到了很多错误,我不知道为什么会这样:注意:这只是一个“测试”代码,它应该只打印下载文件的完成百分比。

def download_file():
    ftp = FTP('exampledomain.com')
    ftp.login(user='user', passwd='pass')

    ftp.cwd('/some_dir/')

    filename = 'file.txt'
    ftp.sendcmd("TYPE i")
    totalsize = ftp.size(filename)
    totalsize = round(totalsize / 1024 / 1024, 1)
    ftp.sendcmd("TYPE A")

    dltracker = FtpDownloadTracker(int(totalsize))
    with open(filename, 'wb') as localfile:
        ftp.retrbinary('RETR ' + filename, localfile.write, 1024, dltracker.handle)

    ftp.quit()
    localfile.close()

class FtpDownloadTracker():
    sizeWritten = 0
    totalSize = 0
    lastPercent = 0

    def __init__(self, totalsize):
        self.totalSize = totalsize

    def handle(self, block):
        self.sizeWritten += 1024
        percentComplete = round((self.sizeWritten / self.totalSize) * 100)

        if self.lastPercent != percentComplete:
            self.lastPercent = percentComplete
            print(str(percentComplete) + " percent complete")

我得到这些错误:

Traceback (most recent call last):
  File "D:/PythonProjects/PythonFTP/ftpdl.py", line 148, in run
    ftp.retrbinary('RETR ' + filename, localfile.write, 1024, dltracker.handle)
  File "C:\Python\lib\ftplib.py", line 442, in retrbinary
    with self.transfercmd(cmd, rest) as conn:
  File "C:\Python\lib\ftplib.py", line 399, in transfercmd
    return self.ntransfercmd(cmd, rest)[0]
  File "C:\Python\lib\ftplib.py", line 364, in ntransfercmd
    self.sendcmd("REST %s" % rest)
  File "C:\Python\lib\ftplib.py", line 273, in sendcmd
    return self.getresp()
  File "C:\Python\lib\ftplib.py", line 246, in getresp
    raise error_perm(resp)
ftplib.error_perm: 554-REST needs a numeric parameter
554 Restart offset reset to 0

我究竟做错了什么?我可以注意到有一个叫做“raise error_perm(resp)”的东西是具有服务器权限的东西还是它是什么?

标签: pythonpython-3.xftpprogress-bar

解决方案


推荐阅读