def draw(cursor, out=sys.stdout, paginate=True, max_fieldsize=100):

    def heading_line(sizes):
        for size in sizes:
            out.write(b'+' + b'-' * (size + 2))
        out.write(b'+\n')

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

    cols, lines = termsize()
    headings = cursor.keys()
    sizes = list(map(lambda x: len(x), headings))
    if paginate:
        cursor = isublists(cursor, lines - 4)
        # else we assume cursor arrive here pre-paginated
    for screenrows in cursor:
        for row in screenrows:
            if row is None:
                break
            for idx, value in enumerate(row):
                if not isinstance(value, basestring):
                    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
                value = rw[idx]
                if not isinstance(value, basestring):
                    value = str(value)
                if len(value) > max_fieldsize:
                    value = value[:max_fieldsize - 5] + '[...]'
                value = value.replace('\n', '^')
                value = value.replace('\r', '^').replace('\t', ' ')
                try:
                    value = fmt % value
                except UnicodeDecodeError:
                    value = fmt % value.decode('utf8')
                out.write(value.encode('utf8'))
            out.write(b'|\n')
        if not paginate:
            heading_line(sizes)
            out.write(b'\n')
Render an result set as an ascii-table.
dataset/ETHPy150Open jaysw/ipydb/ipydb/asciitable.py/draw