示例#1
0
    def show(self):
        if not self.silent:
            ir, iq = divmod(self.amount, self.freq)
            if self.amount <= self.freq or not iq:
                ib = self.amount % _lbar
                #
                if self.prefix: sys.stdout.write(self.prefix)
                sys.stdout.write(_bar_[ib][:-1] + infostr(str(self.amount)) +
                                 '\r')
                sys.stdout.flush()
                return

            for t in (53, 23, 11, 3):
                if t <= ir:
                    ie, ia = divmod(self.amount, t)
                    if ia: return
                    ib = ie % _lbar
                    if self.prefix: sys.stdout.write(self.prefix)
                    sys.stdout.write(_bar_[ib])
                    sys.stdout.flush()
                    return

            if self.prefix: sys.stdout.write(self.prefix)
            ib = self.amount % _lbar
            sys.stdout.write(_bar_[ib])
            sys.stdout.flush()
示例#2
0
文件: table.py 项目: bopopescu/ostap
def table(rows, title='', prefix=''):
    """Format the list of rows as a  table.
    - Each row is a sequence of column cells.
    - The first row defines the column headers.

    When terminaltables package is accessible,
    use it to get nice pretty tables, otherwise use some
    home-made primitive replacement 
    - see https://pypi.org/project/terminaltables
    - see https://github.com/Robpol86/terminaltables

    >>> table_data = [
    ...   ( 'Name'  , 'Occupation' , 'Note' ) ,
    ...   ( 'Alice' , '?'          , '---'  ) ,
    ...   ( 'Bob'   , 'unemployed' , ''     ) ]
    >>> t = table ( table_data , 'Title' )
    >>> print (t)
    """

    from ostap.utils.basic import isatty

    title = allright(decolorize(title))
    if rows:
        rows = list(rows)
        header_row = rows[0]
        header_row = [infostr(decolorize(c)) for c in header_row]
        rows[0] = header_row
        rows = tuple(rows)

    if terminaltables and isatty():

        table_instance = terminaltables.SingleTable(rows, title)
        table_instance.justify_columns[0] = 'left'
        table_instance.justify_columns[2] = 'right'
        return add_prefix(table_instance.table, prefix)

    elif terminaltables:

        title = allright(title)
        table_instance = terminaltables.AsciiTable(rows, title)
        table_instance.justify_columns[0] = 'left'
        table_instance.justify_columns[2] = 'right'
        t = table_instance.table
        return add_prefix(table_instance.table, prefix)

    ## use the local replacement
    return the_table(rows, title, prefix)
示例#3
0
def the_table(rows,
              title='',
              prefix='',
              alignment=(),
              wrap_width=-1,
              indent=wrap_indent):
    """Format the list of rows as a  table (home-made primitive) 
    - Each row is a sequence of column cells.
    - The first row defines the column headers.
    >>> table_data = [
    ...   ( 'Name'  , 'Occupation' , 'Note' ) ,
    ...   ( 'Alice' , '?'          , '---'  ) ,
    ...   ( 'Bob'   , 'unemployed' , ''     ) ]
    >>> t = the_table ( table_data , 'Title' )
    >>> print (t)
    """
    ## calculate the number of columns

    rows = list(rows)

    nc = 0
    for row in rows:
        nc = max(nc, len(row))

    wraps = []
    for i, a in zip(range(nc), alignment):
        if a and isinstance(a, str):
            al = a.lower()
            if al in left: pass
            elif al in right: pass
            elif al in wrapped: wraps.append(i)

    ## calculate the maximum width for columns
    widths = {}
    for k, row in enumerate(rows):
        cols = [c for c in row]
        while len(cols) < nc:
            cols.append('')
        for i, c in enumerate(cols):
            if not i in widths: widths[i] = 1
            widths[i] = max(widths[i], len(decolorize(c)))
        cols = tuple(cols)
        rows[k] = cols

    ## play with wrapped columns
    while wraps:

        twidth = 1 + len(prefix)

        for k in widths:
            if not k in wraps:
                twidth += widths[k] + 2
                twidth += nc + 1
        _, w = terminal_size()
        if w <= twidth: break

        nw = len(wraps)
        ww = (w - twidth) - 2 * nw
        ww, _ = divmod(ww, nw)

        if 12 < wrap_width and wrap_width < ww:
            ww = wrap_width

        if ww < 15: break

        lw = len(wraps)
        wraps = [i for i in wraps if ww <= widths[i]]

        if len(wraps) == lw: break

    for i in wraps:
        widths[i] = min(ww, widths[i])

    hformats = ["{:^%d}" % widths[c] for c in range(nc)]
    rformats = [" {:^%d} " % widths[c] for c in range(nc)]

    for i, a in zip(range(nc), alignment):
        if a and isinstance(a, str):
            al = a.lower()
            if al in left or al in wrapped:
                hformats[i] = hformats[i].replace('^', '<')
                rformats[i] = rformats[i].replace('^', '<')
            elif al in right:
                hformats[i] = hformats[i].replace('^', '>')
                rformats[i] = rformats[i].replace('^', '>')

    if wraps:
        rows_ = rows
        rows = []
        for row in rows_:
            cells = []
            for i, c in enumerate(row):
                if i in wraps and wrap_width < len(c):
                    cells.append(textwrap.wrap(indent + c, widths[i]))
                else:
                    cells.append([c])
            nr = 0
            for c in cells:
                nr = max(nr, len(c))

            for l in cells:
                while len(l) < nr:
                    l.insert(0, '')
                    l.append('')

            for r in range(nr):
                new_row = []
                for i, c in enumerate(cells):
                    lc = len(c)
                    if r < lc: new_row.append(c[r])
                    else: new_row.append('')
                rows.append(new_row)

    totwidth = 0
    for c in widths:
        totwidth += widths[c]
    totwidth += (nc - 1) * 3
    if totwidth < len(title):
        delta = 1 + (len(title) - totwidth) // nc
        for c in widths:
            widths[c] += delta

    seps = ['-' * (widths[c] + 2) for c in range(nc)]
    sepline = '+' + "+".join(seps) + '+'

    table = []
    if title:
        sline = '+' + '-' * (len(sepline) - 2) + '+'
        tfmt = "{:^%d}" % (len(sepline) - 4)
        t = '| ' + allright(tfmt.format(decolorize(title))) + ' |'
        table.append(sline)
        table.append(t)

    table.append(sepline)
    for i, row in enumerate(rows):

        cols = [c for c in row]
        while len(cols) < nc:
            cols.append('')

        if 0 == i:
            table.append('| ' + ' | '.join([
                infostr(f.format(decolorize(i)))
                for (f, i) in zip(hformats, cols)
            ]) + ' |')
            table.append(sepline)
        else:
            table.append('|' + '|'.join(
                [f.format(decolorize(i))
                 for (f, i) in zip(rformats, cols)]) + '|')

    table.append(sepline)

    return prefix + ('\n' + prefix).join(table) if prefix else '\n'.join(table)
示例#4
0
def table(rows,
          title='',
          prefix='',
          alignment=(),
          wrap_width=-1,
          indent=wrap_indent):
    """Format the list of rows as a  table.
    - Each row is a sequence of column cells.
    - The first row defines the column headers.

    When terminaltables package is accessible,
    use it to get nice pretty tables, otherwise use some
    home-made primitive replacement 
    - see https://pypi.org/project/terminaltables
    - see https://github.com/Robpol86/terminaltables

    >>> table_data = [
    ...   ( 'Name'  , 'Occupation' , 'Note' ) ,
    ...   ( 'Alice' , '?'          , '---'  ) ,
    ...   ( 'Bob'   , 'unemployed' , ''     ) ]
    >>> t = table ( table_data , 'Title' )
    >>> print (t)
    """

    from ostap.utils.basic import isatty

    title = allright(decolorize(title))
    if rows:
        rows = list(rows)
        header_row = rows[0]
        header_row = [infostr(decolorize(c)) for c in header_row]
        rows[0] = header_row
        rows = tuple(rows)

    rows = [list(row) for row in rows]

    if not terminaltables:

        ## use the local replacement
        return the_table(rows, title, prefix, alignment=alignment)

    if isatty():

        title = allright(title)
        table_instance = terminaltables.SingleTable(rows, title)

    else:

        title = allright(title)
        table_instance = terminaltables.AsciiTable(rows, title)

    cw = table_instance.column_widths
    nc = len(cw)

    wraps = [i for (i, a) in enumerate(alignment) if a in wrapped]

    if wraps:
        from terminaltables.width_and_alignment import max_dimensions
        widths = max_dimensions(table_instance.table_data,
                                table_instance.padding_left,
                                table_instance.padding_right)[2]
        widths = sum(l for (i, l) in enumerate(widths) if not i in wraps)
        widths += nc + 1 + len(prefix) + 4 + 2 * len(wraps)
        _, w = terminal_size()
        ww = w - widths
        ww, _ = divmod(ww, len(wraps))

        if 12 < ww and ww < wrap_width: wrap_width = ww
        elif 12 < ww and wrap_width <= 0: wrap_width = ww

        if wrap_width < 12: wrap_width = max_width

    nw = len(wraps)

    for i, a in zip(range(nc), alignment):
        if a and isinstance(a, str):
            al = a.lower()
            if al in left: table_instance.justify_columns[i] = 'left'
            elif al in right: table_instance.justify_columns[i] = 'right'
            elif al in center: table_instance.justify_columns[i] = 'center'
            elif al in wrapped:
                maxw = table_instance.column_max_width(i)
                if 15 < wrap_width * nw < maxw:
                    maxw = (wrap_width - 3) * nw if 1 < nw else wrap_width
                if maxw < 15:
                    maxw = (wrap_width - 3) * nw if 1 < nw else wrap_width
                if maxw < 15:
                    maxw = (max_width - 3) * nw if 1 < nw else max_width
                width = maxw / nw if 1 < nw else maxw
                for l, line in enumerate(table_instance.table_data):
                    if width < len(line[i]):
                        table_instance.table_data[l][i] = textwrap.fill(
                            indent + line[i], wrap_width)

    return add_prefix(table_instance.table, prefix)
示例#5
0
文件: table.py 项目: bopopescu/ostap
def the_table(rows, title='', prefix=''):
    """Format the list of rows as a  table (home-made primitive) 
    - Each row is a sequence of column cells.
    - The first row defines the column headers.
    >>> table_data = [
    ...   ( 'Name'  , 'Occupation' , 'Note' ) ,
    ...   ( 'Alice' , '?'          , '---'  ) ,
    ...   ( 'Bob'   , 'unemployed' , ''     ) ]
    >>> t = the_table ( table_data , 'Title' )
    >>> print (t)
    """
    ## calculate the number of columns
    nc = 0
    for row in rows:
        nc = max(nc, len(row))

    ## calculate the maximum width for columns
    widths = {}
    for row in rows:
        cols = [c for c in row]
        while len(cols) < nc:
            cols.append('')
        for i, c in enumerate(cols):
            if not i in widths: widths[i] = 1
            widths[i] = max(widths[i], len(decolorize(c)))

    totwidth = 0
    for c in widths:
        totwidth += widths[c]
    totwidth += (nc - 1) * 3
    if totwidth < len(title):
        delta = 1 + (len(title) - totwidth) // nc
        for c in widths:
            widths[c] += delta

    hformats = ["{:^%d}" % widths[c] for c in range(nc)]
    rformats = [" {:^%d} " % widths[c] for c in range(nc)]

    # the first column is left  adjusted
    rformats[0] = rformats[0].replace('^', '<')
    # the last column  is right adjusted
    rformats[-1] = rformats[-1].replace('^', '>')

    seps = ['-' * (widths[c] + 2) for c in range(nc)]
    sepline = '+' + "+".join(seps) + '+'

    table = []
    if title:
        sline = '+' + '-' * (len(sepline) - 2) + '+'
        tfmt = "{:^%d}" % (len(sepline) - 4)
        t = '| ' + allright(tfmt.format(decolorize(title))) + ' |'
        table.append(sline)
        table.append(t)

    table.append(sepline)
    for i, row in enumerate(rows):

        cols = [c for c in row]
        while len(cols) < nc:
            cols.append('')

        if 0 == i:
            table.append('| ' + ' | '.join([
                infostr(f.format(decolorize(i)))
                for (f, i) in zip(hformats, cols)
            ]) + ' |')
            table.append(sepline)
        else:
            table.append('|' + '|'.join(
                [f.format(decolorize(i))
                 for (f, i) in zip(rformats, cols)]) + '|')

    table.append(sepline)

    return prefix + ('\n' + prefix).join(table) if prefix else '\n'.join(table)
示例#6
0
    def build_bar(self):
        """Figure new percent complete, and rebuild the bar string base on self.amount.
        """
        diff = float(self.amount - self.min)
        done = (diff / float(self.span)) * 100.0
        percent_done = int(round(done))

        # figure the proper number of 'character' make up the bar
        all_full = self.width - 2
        num_hashes = int(round((percent_done * all_full) / 100))

        if 100 <= done and self.__end is None:
            self.__end = time.time()

        if self.__end is None and num_hashes == self._hashes: return False

        eta = ''
        leta = len(eta)
        if self.__end is None and 6 < num_hashes and 1 < done:
            now = time.time()
            feta = int((100 - done) * (now - self.__start) / done)
            h, _ = divmod(feta, 3600)
            m, s = divmod(feta - h * 3600, 60)
            if h: eta = 'ETA %02d:%02d:%02d ' % (h, m, s)
            elif m: eta = 'ETA %02d:%02d ' % (m, s)
            elif s >= 1: eta = 'ETA %02d ' % s
            leta = len(eta)
        elif (not self.__end is None) and 5 < num_hashes:
            now = self.__end
            feta = int(now - self.__start)
            h, _ = divmod(feta, 3600)
            m, s = divmod(feta - h * 3600, 60)
            if h: eta = '%02d:%02d:%02d ' % (h, m, s)
            elif m: eta = '%02d:%02d ' % (m, s)
            elif s >= 1: eta = '%ds ' % s
            leta = len(eta)

        if self.mode == 'dynamic':
            # build a progress bar with self.char (to create a dynamic bar
            # where the percent string moves along with the bar progress.

            if eta and leta < num_hashes:
                self.bar = allright(eta + self.char * (num_hashes - leta))
            else:
                self.bar = allright(self.char * num_hashes)
        else:
            # build a progress bar with self.char and spaces (to create a
            # fixed bar (the percent string doesn't move)
            if eta and leta + 1 < num_hashes:
                self.bar = allright(eta + self.char *
                                    (num_hashes - leta)) + ' ' * (all_full -
                                                                  num_hashes)
            else:
                self.bar = allright(
                    self.char * num_hashes) + ' ' * (all_full - num_hashes)

        percent_str = str(percent_done) + "%"

        self.bar = '[ ' + self.bar + ' ] ' + infostr(percent_str)

        self._hashes = num_hashes
        self._done = done

        return True
示例#7
0
    def __enter__(self):
        self.show()
        return self

    def __exit__(self, *_):
        self.end()

    def __del__(self):
        self.end()


# =============================================================================
_bar_ = (allright('Running ... | ') + '\r', allright('Running ... / ') + '\r',
         allright('Running ... - ') + '\r', allright('Running ... \\ ') + '\r')
_lbar = len(_bar_)
_done_ = infostr('Done            %-d') + '\n'


# =============================================================================
## @class RunningBar
#  - RunningBar
#  @code
#  with RunningBar () as bar :
#    for i in xrange(2000) :
#           ...
#           bar += 1
#  @endcode
#  With helper function:
#  @code
#  for i in running_bar  ( range(10000 ) ) :
#      .. do something here ...