Changeset 433

Show
Ignore:
Timestamp:
05/23/07 19:57:35 (2 years ago)
Author:
athomas
Message:

cly: Applied patch from Wade, closes #47. Thanks.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • cly/trunk/cly/console.py

    r432 r433  
    365365 
    366366def print_table(header, table, sep=' ', indent='', 
    367                 auto_format=('^B^U', '^6', '^B^6'), expand_to_fit=True): 
     367                auto_format=('^B^U', '^6', '^B^6'), expand_to_fit=True, min_widths=None): 
    368368    """Print a list of lists as a table, so that columns line up nicely. 
    369369 
     
    389389        the width of the terminal or compact it as much as possible. If an 
    390390        integer, specifies the width to expand to. 
     391 
     392    ``min_widths``: list of minimum column widths 
     393        Columns will be guaranteed to be at least the width of each element 
     394        in the list. 
    391395 
    392396    Note: ``print_table`` supports the ``^R`` formatting code, in addition to 
     
    404408    table = [[str(c) for c in r] for r in table] 
    405409 
     410    # Make sure min_widths is usable 
     411    min_widths = min_widths or [] 
     412    for i in range(len(min_widths),len(table[0])): 
     413        min_widths.append(0) 
     414 
    406415    rows, cols = len(table), len(table[0]) 
    407416    colwidths = [0] * cols 
    408417    for i in range(0, cols): 
    409418        colwidths[i] = max(map(lambda c: max([0] + map(ctlen, c[i].splitlines())), table)) 
     419        colwidths[i] = max(colwidths[i], min_widths[i]) 
    410420        if i < cols - 1: 
    411421            colwidths[i] += seplen 
     
    413423    # Scale columns if total width is less than the terminal width, or user 
    414424    # requested 
    415     if expand_to_fit in (True, False): 
     425    if expand_to_fit in (None, True, False): 
    416426        max_width = termwidth() - len(indent) 
    417427    else: 
     
    419429        expand_to_fit = True 
    420430 
     431    # Make sure min_widths is sensible 
     432    if sum(min_widths) > max_width: 
     433        raise Exception, 'Table exceeds maximum width' 
     434 
    421435    if expand_to_fit is True or max_width < sum(colwidths): 
    422         scale = float(max_width - 1) / float(sum(colwidths)) 
    423         colwidths = [int(float(x) * scale) for x in colwidths
     436        scale = float(max_width - 1 - sum(min_widths)) / float(sum(colwidths) - sum(min_widths)) 
     437        colwidths = [max(int(float(colwidths[x]) * scale), min_widths[x]) for x in range(0, len(colwidths))
    424438        mincol = min(colwidths) 
    425439        for i, col in enumerate(colwidths):