'Works out the terminal width which is used for word wrapping
some output (eg .help)'

def _terminal_width(self):

    try:
        if (sys.platform == 'win32'):
            import ctypes, struct
            h = ctypes.windll.kernel32.GetStdHandle((-12))
            buf = ctypes.create_string_buffer(22)
            if ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, buf):
                (_, _, _, _, _, left, top, right, bottom, _, _) = struct.unpack('hhhhHhhhhhh', buf.raw)
                return (right - left)
            raise Exception()
        else:
            import struct, fcntl, termios
            s = struct.pack('HHHH', 0, 0, 0, 0)
            x = fcntl.ioctl(2, termios.TIOCGWINSZ, s)
            return struct.unpack('HHHH', x)[1]
    except:
        try:
            v = int(os.getenv('COLUMNS'))
            if (v < 10):
                return 80
            return v
        except:
            return 80
