問題描述
我正在使用以下 Python 腳本通過 FTP 下載文件.我想要的是在下載時查看進度的詳細信息.為此,我使用了 ProgressBar
但它沒有顯示任何內容.
I am downloading files over FTP using the following Python script. What I wanted is to see the details of the progress while downloading. For that I used ProgressBar
but it isn't showing anything.
這是我的代碼:
import re
import os
import ftplib
import ntpath
import sys
import time
from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA,
AdaptiveETA, FileTransferSpeed, FormatLabel, Percentage,
ProgressBar, ReverseBar, RotatingMarker,
SimpleProgress, Timer, UnknownLength
ftp = ftplib.FTP("Your IP address")
ftp.login("Username", "password")
files = []
try:
ftp.cwd("/feed_1")
files = ftp.nlst()
for fname in files:
res = re.findall("2018-07-25", fname)
if res:
print 'Opening local file ' + ntpath.basename(fname)
file = open(ntpath.basename(fname), 'wb')
print 'Getting ' + ntpath.basename(fname)
try:
widgets = ['Downloading: ', Percentage(), ' ',
Bar(marker='#',left='[',right=']'),
' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets, maxval=500)
pbar.start()
ftp.retrbinary('RETR ' + ntpath.basename(fname), file.write)
except:
pass
print 'Closing file ' + ntpath.basename(fname)
file.close()
print (fname)
time.sleep(0.2)
pbar.update()
pbar.finish()
if not res:
continue
except ftplib.error_perm , resp:
if str(resp) == "550 No files found":
print "No files in this directory"
pass
else:
raise
請幫助了解這里的實際問題.謝謝:)
Please help in understanding what's actually wrong here. Thanks :)
推薦答案
你永遠不會更新 ProgressBar
.您需要做的是:
You never update the ProgressBar
. What you need to do is to:
實現一個函數(或類方法),您將傳遞給
FTP.retrbinary
作為callback
而不是file.write
.該函數應該執行file.write
并更新進度條.
Implement a function (or a class method) that you will pass to
FTP.retrbinary
ascallback
instead offile.write
. The function should dofile.write
and also update the progress bar.
您還需要知道 ProgressBar
的 maxval
參數的文件/傳輸的大小.為此,您可以使用 FTP.size
.
You also need to know size of the file/transfer for maxval
argument of ProgressBar
. For that you can use FTP.size
.
一個簡單的實現是這樣的:
A trivial implementation is like:
local_path = "archive.zip"
remote_path = "/remote/path/archive.zip"
file = open(local_path, 'wb')
size = ftp.size(remote_path)
pbar = ProgressBar(widgets=widgets, maxval=size)
pbar.start()
def file_write(data):
file.write(data)
global pbar
pbar += len(data)
ftp.retrbinary("RETR " + remote_path, file_write)
現在你得到了你想要的進度條:
And now you get the progress bar you want:
Downloading: 72% [############################## ] ETA: 0:00:00 242.1 MiB/s
其他人注意:OP 代碼使用 progressbar2
庫.
PyQt 實現:從另一個運行 FTP 下載的線程更新 PyQt 進度.
這篇關于在 Python 中顯示 FTP 下載進度(ProgressBar)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!