def draw(cursor, out=sys.stdout, paginate=True, max_fieldsize=100):
    """Render an result set as an ascii-table.

    Renders an SQL result set to `out`, some file-like object.
    Assumes that we can determine the current terminal height and
    width via the termsize module.

    Args:
        cursor: An iterable of rows. Each row is a list or tuple
                with index access to each cell. The cursor
                has a list/tuple of headings via cursor.keys().
        out: File-like object.
    """

    def heading_line(sizes):
        for size in sizes:
            write_out('+' + '-' * (size + 2), out)
        write_out('+\n', out)

    def draw_headings(headings, sizes):
        heading_line(sizes)
        for idx, size in enumerate(sizes):
            fmt = '| %%-%is ' % size
            write_out((fmt % headings[idx]), out)
        write_out('|\n', out)
        heading_line(sizes)

    cols, lines = termsize()
    headings = list(cursor.keys())
    heading_sizes = [len(str(x)) for x in headings]
    if paginate:
        cursor = isublists(cursor, lines - 4)
        # else we assume cursor arrive here pre-paginated
    for screenrows in cursor:
        sizes = heading_sizes[:]
        for row in screenrows:
            if row is None:
                break
            for idx, value in enumerate(row):
                if not isinstance(value, string_types):
                    value = str(value)
                size = max(sizes[idx], len(value))
                sizes[idx] = min(size, max_fieldsize)
        draw_headings(headings, sizes)
        for rw in screenrows:
            if rw is None:
                break  # from isublists impl
            for idx, size in enumerate(sizes):
                fmt = '| %%-%is ' % size
                if idx < len(rw):
                    value = rw[idx]
                    if not isinstance(value, string_types):
                        value = str(value)
                    if len(value) > max_fieldsize:
                        value = value[:max_fieldsize - 5] + '[...]'
                    value = value.replace('\n', '^')
                    value = value.replace('\r', '^').replace('\t', ' ')
                    value = fmt % value
                    try:
                        value = value.encode('utf-8', 'replace')
                    except __HOLE__:
                        value = fmt % '?'
                    write_out(value, out)
            write_out('|\n', out)
        if not paginate:
            heading_line(sizes)
            write_out('|\n', out)

    out.stdin.flush()
    out.stdin.close()
dataset/ETHPy150Open kristianperkins/x_x/x_x/asciitable.py/draw