Python ftplib:显示FTP上传进度 [英] Python ftplib: Show FTP upload progress

查看:100
本文介绍了Python ftplib:显示FTP上传进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am uploading a large file with FTP using Python 3.4.

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

I would like to be able to show the progress percentage while uploading the file. Here's my code:

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函数中获取已经读取的块数?

How to have the number of blocks already read in the handle function?

阅读 cmd 的回答后,我将其添加到我的代码中:

After reading cmd's answer, I added this to my code:

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 上传:

And I call the FTP upload like this :

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

推荐答案

我能想到三种非hacky 的方法.然后所有这些都改变了变量的所有权":

There are three non-hacky ways I can think of. All of then shift the "ownwership" of the variable:

  1. 传入值并返回结果(基本上意味着它存储在调用者中)
  2. 将值设为全局,并将其初始化为 0 和文件顶部.(阅读 global 关键字)
  3. 将此函数作为类的成员函数来处理上传跟踪.然后使 sizeWritten 成为该类的实例变量.
  1. have the value passed in and return the result (basically means its stored in the caller)
  2. have the value be global, and initialize it to 0 and the top of your file. (read up on the global keyword)
  3. have this function as a member function of a class to handle upload tracking. Then make sizeWritten a instance variable of that class.

这篇关于Python ftplib:显示FTP上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆