Mar*_*low 2 python ftp download ftplib progress-bar
我正在使用以下Python脚本通过FTP下载文件。我想要的是在下载时查看进度的详细信息。为此,我使用了ProgressBar它,但没有显示任何内容。
这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
请帮助您了解此处的实际错误。谢谢 :)
您永远不会更新ProgressBar。您需要做的是:
实现一个函数(或一个类的方法),您将传递给FTP.retrbinary作为callback代替file.write。该功能应该执行file.write并更新进度条。
您还需要知道文件/传输的大小作为maxval参数ProgressBar。为此,您可以使用FTP.size。
一个简单的实现就像:
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)
Run Code Online (Sandbox Code Playgroud)
现在,您将获得所需的进度栏:
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)
Run Code Online (Sandbox Code Playgroud)
其他说明:OP代码使用progressbar2library。
PyQt实现:从另一个运行FTP下载的线程更新PyQt进度。