【问题标题】:Python ftplib: Show FTP upload progressPython ftplib:显示 FTP 上传进度
【发布时间】:2014-02-24 20:13:57
【问题描述】:

我正在使用 Python 3.4 通过 FTP 上传一个大文件。

我希望能够在上传文件时显示进度百分比。这是我的代码:

from ftplib import FTP
import os.path

# Init
sizeWritten = 0
totalSize = os.path.getsize('test.zip')
print('Total file size : ' + str(round(totalSize / 1024 / 1024 ,1)) + ' Mb')

# Define a handle to print the percentage uploaded
def handle(block):
    sizeWritten += 1024 # this line fail because sizeWritten is not initialized.
    percentComplete = sizeWritten / totalSize
    print(str(percentComplete) + " percent complete")

# Open FTP connection
ftp = FTP('website.com')
ftp.login('user','password')

# Open the file and upload it
file = open('test.zip', 'rb')
ftp.storbinary('STOR test.zip', file, 1024, handle)

# Close the connection and the file
ftp.quit()
file.close()

如何在句柄函数中获得已经读取的块数?

更新

在阅读了 cmd 的回答后,我将这个添加到我的代码中:

class FtpUploadTracker:
    sizeWritten = 0
    totalSize = 0
    lastShownPercent = 0
    
    def __init__(self, totalSize):
        self.totalSize = totalSize
    
    def handle(self, block):
        self.sizeWritten += 1024
        percentComplete = round((self.sizeWritten / self.totalSize) * 100)
        
        if (self.lastShownPercent != percentComplete):
            self.lastShownPercent = percentComplete
            print(str(percentComplete) + " percent complete")

我这样调用 FTP 上传:

uploadTracker = FtpUploadTracker(int(totalSize))
ftp.storbinary('STOR test.zip', file, 1024, uploadTracker.handle)

【问题讨论】:

  • 用 Python 创建进度条:thelivingpearl.com/2012/12/31/…
  • 对于 Python 2,您需要将 percentComplete 行更改为:percentComplete = round((float(self.sizeWritten) / float(self.totalSize)) * 100)
  • 有一个模块叫progressbar。我还没有检查它是否可以与 ftplib 一起使用,但无论如何它是一个非常完整的模块来呈现进度条
  • 嘿,谢谢,这正是我所需要的!一个问题:每次都会打印一个新行,一个新数字。我可以在同一个地方只更新一个号码吗? @cmd 没关系,我在这里找到了stackoverflow.com/questions/517127/…
  • 好的,现在我明白了。 session.storbinary('STOR '+upload_file, file, 1024, uploadTrack.handler) 这里的处理程序有 2 个参数,实例名称和块大小,即 1024。然后我做了这样的:`def handler(self, chunk): self.size_written += len(chunk)

标签: python python-3.4


【解决方案1】:

我能想到三种非 hacky 的方式。然后全部转移变量的“所有权”:

  1. 将值传入并返回结果(基本上是指它存储在调用者中)
  2. 具有全局值,并将其初始化为 0 和文件的顶部。 (阅读 global 关键字)
  3. 将此函数作为类的成员函数来处理上传跟踪。然后将sizeWritten 设为该类的实例变量。

【讨论】:

  • 我使用了解决方案 #3,它有效,我将使用工作代码更新我的问题。
  • @Gab: option: 3* 使用nonlocal sent_bytes 进行闭包,例如make_counter()
  • 正如@J.F.Sebastian 建议的那样,我已经使用非本地完成了这项工作。你可以在这里看到它(寻找 print_transfer_status 方法):bitbucket.org/dkurth/ftp_connection.py
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多