'Return the terminal width if possible, otherwise return 0.'

def terminal_width(self):

    ncols = 0
    try:
        import curses
        import io
        try:
            curses.setupterm()
            ncols = curses.tigetnum('cols')
        except AttributeError:
            from ctypes import windll, create_string_buffer
            h = windll.kernel32.GetStdHandle((-12))
            csbi = create_string_buffer(22)
            res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
            if res:
                import struct
                (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack('hhhhHhhhhhh', csbi.raw)
                ncols = ((right - left) + 1)
        except curses.error:
            pass
        except io.UnsupportedOperation:
            pass
    except (ImportError, TypeError):
        pass
    return ncols
