def _get_terminal_size():
        """Find current STDOUT's width, in characters."""
        # If output is not terminal but a regular file, assume 100 chars width
        if not sys.stdout.isatty():
            return 80

        # Otherwise, first try getting the dimensions from shell command `stty`:
        try:
            import subprocess
            ret = subprocess.check_output(["stty", "size"]).strip().split(" ")
            if len(ret) == 2:
                return int(ret[1])
        except:
            pass

        # Otherwise try using ioctl
        try:
            from termios import TIOCGWINSZ
            from fcntl import ioctl
            from struct import unpack
            res = unpack("hh", ioctl(sys.stdout, TIOCGWINSZ, b"1234"))
            return int(res[1])
        except:
            pass

        # Finally check the COLUMNS environment variable
        return int(os.environ.get("COLUMNS", 80))
Find current STDOUT's width, in characters.