#!/usr/bin/env python import time import empty import thr import dbg def cnt_new(n): e = empty.new() e.i = 0 e.p = 0 e.s_n = 0 e.st_sec = None e.st_i = None e.ed_sec = None def calc_rsec(): now = time.time() i = e.i rsec = -1 if e.st_sec is None: e.st_sec = now e.st_i = i else: rsec = ( now - e.st_sec ) * ( n - i ) / ( i - e.st_i ) return rsec def sec_to_str(sec): v = int( sec ) s = '' while v > 0: a = str( v % 60 ) v = v // 60 if v > 0: a = ':' + ( '0' + a )[ -2 : ] s = a + s return s def show(s): bk = '\b' * e.s_n bk = bk + ( ' ' * e.s_n ) + bk e.s_n = len( s ) dbg.out( bk + s, '' ) def th_f(): p = int( 100 * e.i / n ) if p > e.p: e.p = p show( '{}% rest {}'.format( p, sec_to_str( calc_rsec() ) ) ) th = thr.loop_new( th_f, wait_tmout=1.0 ) thr.ths.start( th ) def up(): if e.i < n: e.i += 1 if e.i == n: e.ed_sec = time.time() def show_all_sec(fmt): st_sec = e.st_sec if e.st_sec else time.time() ed_sec = e.ed_sec if e.ed_sec else time.time() s = sec_to_str( ed_sec - st_sec ) dbg.out( fmt.format( s ) ) def stop(show_fmt=''): show( '' ) th.quit_ev.set() if show_fmt: show_all_sec( show_fmt ) return empty.add( e, locals() ) def cnt_map(func, lst, show_fmt=''): cnt = cnt_new( len( lst ) ) def f(v): cnt.up() return func( v ) rlst = map( f, lst ) cnt.stop( show_fmt ) return rlst def cnt_loop(func_i, n, show_fmt=''): cnt = cnt_new( n ) for i in range( n ): cnt.up() func_i( i ) cnt.stop( show_fmt ) # EOF