Get the terminal size of a UNIX terminal using the ioctl UNIX command.

def get_unix_ioctl_terminal_size():
    """Get the terminal size of a UNIX terminal using the ioctl UNIX command."""
    def ioctl_gwinsz(fd):
        try:
            import fcntl
            import termios
            import struct
            return struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
        except (IOError, OSError):
            return None

    cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)
    if not cr:
        try:
            f = open(os.ctermid())
            cr = ioctl_gwinsz(f.fileno())
            f.close()
        except (IOError, OSError):
            pass
    if not cr:
        try:
            cr = (os.environ['LINES'], os.environ['COLUMNS'])
        except KeyError:
            return None
    return int(cr[1]), int(cr[0])