Python中如何显示FTP上传进度条

3
所以我正在编写一个脚本,用于递归搜索文件夹中的 .mkv 文件并将其上传到我的 NAS。我已经让脚本运行但是我看不到进度。我导入了这个在 github 上找到的 progressbar,并且能够使用演示看到它工作。这就是我想要的,然而他们包含的 FTP 示例是从服务器检索文件,而我需要上传。

如何获取上传量并在间隔上运行更新以更新进度条?

下面是我已经为上传准备好的代码:

import os
import ftplib
import ntpath

ntpath.basename("a/b/c")

def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        print file
        TheFile = open(file, 'r')
        ftp.storbinary('STOR ' + FileName, TheFile, 1024)
        TheFile.close()
    ftp.quit()
    ftp = None

FTP_GLOB_transfer('<IP>', '<USER>', '<PASSWORD>')
1个回答

8
我已经想通了。我决定使用TQDM,因为我发现它有更易于阅读的文档。我一直认为storbinary()必须有一个返回值或其他东西来告诉它的进度,只是不知道我在寻找回调函数。
无论如何,我添加了一个新的导入from tqdm import tqdm 我添加了这个filesize = os.path.getsize(file)来获取文件的大小
然后我用这段代码替换了ftp.storbinary('STOR ' + FileName, TheFile, 1024)
with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
        ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))

总体来说,新的工作代码看起来像这样:

import os
import ftplib
import ntpath
from tqdm import tqdm

ntpath.basename("a/b/c")

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        filesize = os.path.getsize(file)
        print file
        TheFile = open(file, 'r')
        with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
            ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
        TheFile.close()
    ftp.quit()
    ftp = None

现在的输出结果如下:

/tmp/rippedMovies/TestMovie.mkv
Uploading......:  51%|████████████████████▉                    | 547M/1.07G 
[00:05<00:14, 36.8Mblocks/s]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接