modified progressbar

develop
Спиридонов Денис 12 years ago
parent 0ae9c6c9a1
commit 40048baf1f

@ -15,12 +15,16 @@
# limitations under the License.
import time, os, sys, re
from fcntl import ioctl
from array import array
import termios
import subprocess
from OpenSSL import crypto
import shlex
from sudsds import MethodNotFound
from calculate.core.server.cert_cmd import getHwAddr, getIpLocal
from progressbar import Bar, Percentage, ETA, ProgressBar
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('calculate_console',sys.modules[__name__])
from calculate.core.client.function import create_obj
@ -467,6 +471,11 @@ def get_entire_frame(client, pid):
end_frame = get_message(client, item, sid, pid)
def get_Progress(client, sid, pid, id):
widgets = ['','', Bar(), '', Percentage(),' ', ETA()]
pbar = ProgressBar(widgets=widgets, maxval=100)
# maybe do something
pbar.start()
""" get progress for the current job """
returnProgr = client.service.get_progress(sid, pid, id)
temp_progress = -1
@ -474,7 +483,10 @@ def get_Progress(client, sid, pid, id):
percent = returnProgr.percent
while percent <= 100 and percent >= 0 :
if temp_progress != percent:
last_message = print_progress(returnProgr, last_msg = last_message)
# last_message = print_progress(returnProgr, last_msg = last_message)
last_message = print_progressbar(returnProgr, pbar,
last_msg = last_message)
# pbar.update(returnProgr.percent)
if percent == 100:
print
return
@ -483,26 +495,39 @@ def get_Progress(client, sid, pid, id):
returnProgr = client.service.get_progress(sid, pid, id)
percent = returnProgr.percent
if percent < 0:
print_progress(returnProgr, error = True)
# print_progress(returnProgr, error = True)
pbar.update(0 - returnProgr.percent)
pbar.finish()
else:
print_progress(returnProgr)
#def cout(string):
# sys.stdout.write(string)
# sys.stdout.flush()
#
#for perc in xrange(101):
# cout ('\r' + str(perc / 1.0).rjust(5) + '% ')
# time.sleep(.2)
# print_progress(returnProgr)
pbar.update(returnProgr.percent)
pbar.finish()
def cout_progress(string):
sys.stdout.write('\b\b\b\b\b\b' + string)
h,w=array('h', ioctl(sys.stderr,termios.TIOCGWINSZ,'\0'*8))[:2]
sys.stdout.write('\r' + (' '*(w)))
sys.stdout.write('\r' + string)
sys.stdout.flush()
def cout(string):
sys.stdout.write(string)
sys.stdout.flush()
def print_progressbar(returnProgr, pbar, last_msg = None, error = False):
if returnProgr.long_message:
if last_msg != returnProgr.long_message:
cout_progress('%s\n' %returnProgr.long_message)
pbar.update(returnProgr.percent)
return returnProgr.long_message
elif returnProgr.short_message:
if last_msg != returnProgr.short_message:
cout_progress('%s\n' %returnProgr.short_message)
pbar.update(returnProgr.percent)
return returnProgr.short_message
else:
pbar.update(returnProgr.percent)
return last_msg
def print_progress(returnProgr, last_msg = None, error = False):
if error:
cout_progress ('\n'+_("Error task by %s") \

@ -0,0 +1,165 @@
# -*- coding: utf-8 -*-
import sys, time
from array import array
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('calculate_console',sys.modules[__name__])
try:
from fcntl import ioctl
import termios
except ImportError:
pass
import signal
class ProgressBarWidget(object):
def update(self, pbar):
pass
class ProgressBarWidgetHFill(object):
def update(self, pbar, width):
pass
class ETA(ProgressBarWidget):
"Widget for the Estimated Time of Arrival"
def format_time(self, seconds):
return time.strftime('%H:%M:%S', time.gmtime(seconds))
def update(self, pbar):
if pbar.currval == 0:
return _('Time').decode('utf-8') + ': --:--:--'
elif pbar.finished:
return _('Time').decode('utf-8') + ': %s' \
%self.format_time(pbar.seconds_elapsed)
else:
# elapsed = pbar.seconds_elapsed
# eta = elapsed * pbar.maxval / pbar.currval - elapsed
return _('Time').decode('utf-8') + ': %s' \
%self.format_time(pbar.seconds_elapsed)
class FileTransferSpeed(ProgressBarWidget):
"Widget for showing the transfer speed (useful for file transfers)."
def __init__(self):
self.fmt = '%6.2f %s'
self.units = ['B','K','M','G','T','P']
def update(self, pbar):
if pbar.seconds_elapsed < 2e-6:#== 0:
bps = 0.0
else:
bps = float(pbar.currval) / pbar.seconds_elapsed
spd = bps
for u in self.units:
if spd < 1000:
break
spd /= 1000
return self.fmt % (spd, u+'/s')
class Percentage(ProgressBarWidget):
"Just the percentage done."
def update(self, pbar):
return '%3d%%' % pbar.percentage()
class Bar(ProgressBarWidgetHFill):
"The bar of progress. It will strech to fill the line."
def __init__(self, marker='=', left='[', right=']'):
self.marker = marker
self.left = left
self.right = right
def _format_marker(self, pbar):
if isinstance(self.marker, (str, unicode)):
return self.marker
else:
return self.marker.update(pbar)
def update(self, pbar, width):
percent = pbar.percentage()
cwidth = width - len(self.left) - len(self.right)
marked_width = int(percent * cwidth / 100)
m = self._format_marker(pbar)
bar = (self.left + (m*(marked_width-1)+'>').ljust(cwidth)+self.right)
return bar
default_widgets = [Percentage(), ' ', Bar()]
class ProgressBar(object):
def __init__(self, maxval=100, widgets=default_widgets, term_width=None,
fd=sys.stderr):
assert maxval > 0
self.maxval = maxval
self.widgets = widgets
self.fd = fd
self.signal_set = False
if term_width is None:
try:
self.handle_resize(None,None)
signal.signal(signal.SIGWINCH, self.handle_resize)
self.signal_set = True
except:
self.term_width = 99
else:
self.term_width = term_width
self.currval = 0
self.finished = False
self.prev_percentage = -1
self.start_time = None
self.seconds_elapsed = 0
def handle_resize(self, signum, frame):
h, self.term_width = array('h', ioctl(self.fd,termios.TIOCGWINSZ,
'\0'*8))[:2]
def percentage(self):
"Returns the percentage of the progress."
return self.currval*100.0 / self.maxval
def _format_widgets(self):
r = []
hfill_inds = []
num_hfill = 0
currwidth = 0
for i, w in enumerate(self.widgets):
if isinstance(w, ProgressBarWidgetHFill):
r.append(w)
hfill_inds.append(i)
num_hfill += 1
elif isinstance(w, (str, unicode)):
r.append(w)
currwidth += len(w)
else:
weval = w.update(self)
currwidth += len(weval)
r.append(weval)
for iw in hfill_inds:
r[iw] = r[iw].update(self, (self.term_width-currwidth)/num_hfill)
return r
def _format_line(self):
return ''.join(self._format_widgets()).ljust(self.term_width)
def _need_update(self):
return int(self.percentage()) != int(self.prev_percentage)
def update(self, value):
"Updates the progress bar to a new value."
assert 0 <= value <= self.maxval
self.currval = value
if not self._need_update() or self.finished:
return
if not self.start_time:
self.start_time = time.time()
self.seconds_elapsed = time.time() - self.start_time
self.prev_percentage = self.percentage()
if value != self.maxval:
self.fd.write(self._format_line() + '\r')
else:
self.finished = True
self.fd.write(self._format_line() + '\n')
def start(self):
self.update(0)
return self
def finish(self):
"""Used to tell the progress is finished."""
self.update(self.maxval)
if self.signal_set:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)

@ -2,8 +2,8 @@ msgid ""
msgstr ""
"Project-Id-Version: console_gui_translate\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-09 16:19+0300\n"
"PO-Revision-Date: 2012-06-09 16:19+0300\n"
"POT-Creation-Date: 2012-06-13 12:57+0300\n"
"PO-Revision-Date: 2012-06-13 12:57+0300\n"
"Last-Translator: Denis <ds@mail.ru>\n"
"Language-Team: \n"
"Language: \n"
@ -15,6 +15,11 @@ msgstr ""
"X-Poedit-SourceCharset: utf-8\n"
"X-Poedit-SearchPath-0: /var/calculate/mydir/git/calculate-console/console/application\n"
#: /var/calculate/mydir/git/calculate-console/console/application/progressbar.py:36
#: /var/calculate/mydir/git/calculate-console/console/application/progressbar.py:42
msgid "Time"
msgstr "Время"
#: /var/calculate/mydir/git/calculate-console/console/application/pid_information.py:29
msgid "PID not found"
msgstr "Процесс не найден"
@ -212,7 +217,7 @@ msgstr "сервер послал идентификатор процесса =
msgid "Process not exist or not belong to your session"
msgstr "Процесс не существует или принадлежит не вашей сессии"
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:508
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:500
#, python-format
msgid "Error task by %s"
msgstr "Ошибка задачи на %s"

Loading…
Cancel
Save