gpt4 book ai didi

python ftplib : Show FTP upload progress

转载 作者:太空狗 更新时间:2023-10-29 21:50:05 25 4
gpt4 key购买 nike

我正在使用 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()

如何在handle函数中获取已经读取的 block 数?

更新

在阅读 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)

最佳答案

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

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

关于 python ftplib : Show FTP upload progress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com