Python shutil.get_terminal_size() Examples

The following are 30 code examples of shutil.get_terminal_size(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module shutil , or try the search function .
Example #1
Source File: terminal.py    From recruit with Apache License 2.0 6 votes vote down vote up
def get_terminal_size():
    """
    Detect terminal size and return tuple = (width, height).

    Only to be used when running in a terminal. Note that the IPython notebook,
    IPython zmq frontends, or IDLE do not run in a terminal,
    """
    import platform

    if PY3:
        return shutil.get_terminal_size()

    current_os = platform.system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if (current_os == 'Linux' or current_os == 'Darwin' or
            current_os.startswith('CYGWIN')):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        tuple_xy = (80, 25)      # default value
    return tuple_xy 
Example #2
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_pp(self, arg):
        """[width]pp expression
        Pretty-print the value of the expression.
        """
        width = getattr(arg, "cmd_count", None)
        try:
            val = self._getval(arg)
        except:
            return
        if width is None:
            try:
                width, _ = self.get_terminal_size()
            except Exception as exc:
                self.message("warning: could not get terminal size ({})".format(exc))
                width = None
        try:
            pprint.pprint(val, self.stdout, width=width)
        except:
            exc_info = sys.exc_info()[:2]
            self.error(traceback.format_exception_only(*exc_info)[-1].strip()) 
Example #3
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_terminal_size():
        fallback = (80, 24)
        try:
            from shutil import get_terminal_size
        except ImportError:
            try:
                import termios
                import fcntl
                import struct
                call = fcntl.ioctl(0, termios.TIOCGWINSZ, "\x00"*8)
                height, width = struct.unpack("hhhh", call)[:2]
            except (SystemExit, KeyboardInterrupt):
                raise
            except:
                width = int(os.environ.get('COLUMNS', fallback[0]))
                height = int(os.environ.get('COLUMNS', fallback[1]))
            # Work around above returning width, height = 0, 0 in Emacs
            width = width if width != 0 else fallback[0]
            height = height if height != 0 else fallback[1]
            return width, height
        else:
            return get_terminal_size(fallback) 
Example #4
Source File: util.py    From GetSubtitles with MIT License 6 votes vote down vote up
def refresh(self, cur_len):
        terminal_width = get_terminal_size().columns  # 获取终端宽度
        info = "%s '%s'...  %.2f%%" % (
            self.prefix_info,
            self.title,
            cur_len / self.total * 100,
        )
        while len(info) > terminal_width - 20:
            self.title = self.title[0:-4] + "..."
            info = "%s '%s'...  %.2f%%" % (
                self.prefix_info,
                self.title,
                cur_len / self.total * 100,
            )
        end_str = "\r" if cur_len < self.total else "\n"
        print(info, end=end_str) 
Example #5
Source File: terminal.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def get_terminal_size():
    """
    Detect terminal size and return tuple = (width, height).

    Only to be used when running in a terminal. Note that the IPython notebook,
    IPython zmq frontends, or IDLE do not run in a terminal,
    """
    import platform

    if PY3:
        return shutil.get_terminal_size()

    current_os = platform.system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if (current_os == 'Linux' or current_os == 'Darwin' or
            current_os.startswith('CYGWIN')):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        tuple_xy = (80, 25)      # default value
    return tuple_xy 
Example #6
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_stty_match(self):
        """Check if stty returns the same results ignoring env

        This test will fail if stdin and stdout are connected to
        different terminals with different sizes. Nevertheless, such
        situations should be pretty rare.
        """
        try:
            size = subprocess.check_output(['stty', 'size']).decode().split()
        except (FileNotFoundError, subprocess.CalledProcessError):
            self.skipTest("stty invocation failed")
        expected = (int(size[1]), int(size[0])) # reversed order

        with support.EnvironmentVarGuard() as env:
            del env['LINES']
            del env['COLUMNS']
            actual = shutil.get_terminal_size()

        self.assertEqual(expected, actual) 
Example #7
Source File: util.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def get_data(self, wrap=True):
        if wrap:
            terminal_size = shutil.get_terminal_size((80, 40))
            wrap_columns = terminal_size.columns
            if wrap_columns > int(config.CONFIG.parser['info_display_max_columns']):
                wrap_columns = int(config.CONFIG.parser['info_display_max_columns'])
            return '\n'.join([textwrap.fill(x, wrap_columns) for x in ''.join(self.fed).split('\n')])
        return ''.join(self.fed) 
Example #8
Source File: terminal.py    From autohooks with GNU General Public License v3.0 5 votes vote down vote up
def get_width() -> int:
        """
        Get the width of the terminal window
        """
        width, _ = shutil.get_terminal_size(TERMINAL_SIZE_FALLBACK)
        return width 
Example #9
Source File: misc.py    From Rebaler with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, prog):
        terminal_width = shutil.get_terminal_size().columns
        os.environ['COLUMNS'] = str(terminal_width)
        max_help_position = min(max(24, terminal_width // 3), 40)
        super().__init__(prog, max_help_position=max_help_position) 
Example #10
Source File: terminalwriter.py    From py with MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example #11
Source File: default.py    From schemathesis with MIT License 5 votes vote down vote up
def get_terminal_width() -> int:
    return shutil.get_terminal_size().columns 
Example #12
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_exc_for_sticky(self, exc):
        if len(exc) != 2:
            return "pdbpp: got unexpected __exception__: %r" % (exc,)

        exc_type, exc_value = exc
        s = ''
        try:
            try:
                s = exc_type.__name__
            except AttributeError:
                s = str(exc_type)
            if exc_value is not None:
                s += ': '
                s += str(exc_value)
        except KeyboardInterrupt:
            raise
        except Exception as exc:
            try:
                s += '(unprintable exception: %r)' % (exc,)
            except:
                s += '(unprintable exception)'
        else:
            # Use first line only, limited to terminal width.
            s = s.replace("\r", r"\r").replace("\n", r"\n")
            width, _ = self.get_terminal_size()
            if len(s) > width:
                s = s[:width - 1] + "…"

        if self.config.highlight:
            s = Color.set(self.config.line_number_color, s)

        return s 
Example #13
Source File: terminalwriter.py    From python-netsurv with MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example #14
Source File: terminalwriter.py    From python-netsurv with MIT License 5 votes vote down vote up
def _getdimensions():
    if py33:
        import shutil
        size = shutil.get_terminal_size()
        return size.lines, size.columns
    else:
        import termios, fcntl, struct
        call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
        height, width = struct.unpack("hhhh", call)[:2]
        return height, width 
Example #15
Source File: search.py    From pdm with MIT License 5 votes vote down vote up
def handle(self, project: Project, options: argparse.Namespace) -> None:
        result = project.get_repository().search(options.query)
        terminal_width = None
        if sys.stdout.isatty():
            terminal_width = get_terminal_size()[0]
        print_results(result, project.environment.get_working_set(), terminal_width) 
Example #16
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example #17
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #18
Source File: __init__.py    From phpsploit with GNU General Public License v3.0 5 votes vote down vote up
def size(fallback=(80, 24)) -> tuple:
    """Get the size of the terminal window."""
    return tuple(shutil.get_terminal_size(fallback=fallback)) 
Example #19
Source File: terminal.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_terminal_size():
    """
    Detect terminal size and return tuple = (width, height).

    Only to be used when running in a terminal. Note that the IPython notebook,
    IPython zmq frontends, or IDLE do not run in a terminal,
    """
    import platform

    if PY3:
        return shutil.get_terminal_size()

    current_os = platform.system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if current_os == 'Linux' or \
        current_os == 'Darwin' or \
            current_os.startswith('CYGWIN'):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        tuple_xy = (80, 25)      # default value
    return tuple_xy 
Example #20
Source File: compat.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example #21
Source File: compat.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #22
Source File: compat.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size()) 
Example #23
Source File: compat.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #24
Source File: _compat.py    From psutil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_terminal_size(fallback=(80, 24)):
        try:
            import fcntl
            import termios
            import struct
        except ImportError:
            return fallback
        else:
            try:
                # This should work on Linux.
                res = struct.unpack(
                    'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234'))
                return (res[1], res[0])
            except Exception:
                return fallback 
Example #25
Source File: util.py    From BasicSR with Apache License 2.0 5 votes vote down vote up
def _get_max_bar_width(self):
        terminal_width, _ = get_terminal_size()
        max_bar_width = min(int(terminal_width * 0.6), terminal_width - 50)
        if max_bar_width < 10:
            print('terminal width is too small ({}), please consider widen the terminal for better '
                  'progressbar visualization'.format(terminal_width))
            max_bar_width = 10
        return max_bar_width 
Example #26
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size())  # type: ignore 
Example #27
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except Exception:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except Exception:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #28
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        return tuple(shutil.get_terminal_size())  # type: ignore 
Example #29
Source File: compat.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_terminal_size():
        # type: () -> Tuple[int, int]
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except Exception:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except Exception:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #30
Source File: progress_bar.py    From TENet with MIT License 5 votes vote down vote up
def _get_max_bar_width(self):
        terminal_width, _ = get_terminal_size()
        max_bar_width = min(int(terminal_width * 0.6), terminal_width - 50)
        if max_bar_width < 10:
            print('terminal width is too small ({}), please consider widen the terminal for better '
                  'progressbar visualization'.format(terminal_width))
            max_bar_width = 10
        return max_bar_width