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: 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 #2
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 #3
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 #4
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 #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: 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 #7
Source File: target.py    From iris with Mozilla Public License 2.0 5 votes vote down vote up
def pytest_sessionfinish(self, session):
        """ called after whole test run finished, right before returning the exit status to the system.

        :param _pytest.main.Session session: the pytest session object.
        :param int exitstatus: the status which pytest will return to the system.
        """
        for test in self.completed_tests:
            if test.outcome == "FAILED" or test.outcome == "ERROR":
                self.clean_run = False

        self.end_time = time.time()

        update_run_index(self, True)
        footer = create_footer(self)
        result = footer.print_report_footer()
        create_run_log(self)

        logger.info(
            "\n"
            + "Test session {} complete".format(session.name).center(
                shutil.get_terminal_size().columns, "-"
            )
        )

        if core_args.email:
            try:
                submit_email_report(self, result)
            except SyntaxError:
                logger.error(
                    "Problem with email report - check config file for correct values."
                ) 
Example #8
Source File: cli.py    From cot with MIT License 5 votes vote down vote up
def terminal_width(self):
        """Get the width of the terminal in columns."""
        if self._terminal_width is None:
            try:
                self._terminal_width = get_terminal_size().columns
            except ValueError:
                # sometimes seen in unit tests:
                # ValueError: underlying buffer has been detached
                # Easy enough to work around...
                self._terminal_width = 80
            if self._terminal_width <= 0:
                self._terminal_width = 80
        return self._terminal_width 
Example #9
Source File: console.py    From rich with MIT License 5 votes vote down vote up
def size(self) -> ConsoleDimensions:
        """Get the size of the console.

        Returns:
            ConsoleDimensions: A named tuple containing the dimensions.
        """
        if self._width is not None and self._height is not None:
            return ConsoleDimensions(self._width, self._height)

        width, height = shutil.get_terminal_size()
        return ConsoleDimensions(
            (width - self.legacy_windows) if self._width is None else self._width,
            height if self._height is None else self._height,
        ) 
Example #10
Source File: _backprop_utils.py    From chainer with MIT License 5 votes vote down vote up
def _get_columns():
    # Returns the terminal column width.
    if sys.version_info >= (3, 3):
        cols, rows = shutil.get_terminal_size()
        return cols
    return int(os.getenv('COLUMNS', 80)) 
Example #11
Source File: progressbar.py    From mmcv with Apache License 2.0 5 votes vote down vote up
def terminal_width(self):
        width, _ = get_terminal_size()
        return width 
Example #12
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_does_not_crash(self):
        """Check if get_terminal_size() returns a meaningful value.

        There's no easy portable way to actually check the size of the
        terminal, so let's check if it returns something sensible instead.
        """
        size = shutil.get_terminal_size()
        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example #13
Source File: compat.py    From hacktoberfest2018 with GNU General Public License v3.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 #14
Source File: util.py    From IKC 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 #15
Source File: help_formatter.py    From Deepbinner 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)
        try:
            self.colours = int(subprocess.check_output(['tput', 'colors']).decode().strip())
        except (ValueError, subprocess.CalledProcessError, FileNotFoundError, AttributeError):
            self.colours = 1
        super().__init__(prog, max_help_position=max_help_position) 
Example #16
Source File: misc.py    From ParlAI with MIT License 5 votes vote down vote up
def _line_width():
    try:
        # if we're in an interactive ipython notebook, hardcode a longer width
        __IPYTHON__
        return 128
    except NameError:
        return shutil.get_terminal_size((88, 24)).columns 
Example #17
Source File: compat.py    From pySINDy 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 #18
Source File: compat.py    From pySINDy 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 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 #19
Source File: target.py    From iris with Mozilla Public License 2.0 5 votes vote down vote up
def pytest_sessionstart(self, session):
        """Called after the 'Session' object has been created and before performing test collection.

        :param _pytest.main.Session session: the pytest session object.
        """
        self.start_time = time.time()
        logger.info(
            "\n"
            + "Test session {} started".format(session.name).center(
                shutil.get_terminal_size().columns, "-"
            )
        )

        core_settings_list = []
        for arg in vars(core_args):
            core_settings_list.append("{}: {}".format(arg, getattr(core_args, arg)))
        logger.info("\nIris settings:\n" + ", ".join(core_settings_list))

        target_settings_list = []

        for arg in vars(self.args):
            target_settings_list.append("{}: {}".format(arg, getattr(self.args, arg)))
        logger.info(
            ("\n{} settings:\n" + ", ".join(target_settings_list)).format(
                str(core_args.target).capitalize()
            )
        )
        update_run_index(self, False) 
Example #20
Source File: wechit.py    From wechit with MIT License 5 votes vote down vote up
def get_term_shape():
    global TERM_ROWS, TERM_COLUMNS
    if IS_PYTHON3:
        result = tuple(reversed(list(shutil.get_terminal_size((TERM_COLUMNS, TERM_ROWS)))))
    else:
        result = tuple([int(x) for x in os.popen('stty size', 'r').read().split()])
    TERM_ROWS,TERM_COLUMNS = result
    return result

# retrieve a function for mapping RGB values to ANSI color escape codes 
Example #21
Source File: compat.py    From GraphicDesignPatternByPython 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 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 #22
Source File: util.py    From real-world-sr 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 
Example #23
Source File: compat.py    From pipenv 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:
            if sys.platform != "win32":
                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 #24
Source File: compat.py    From pipenv 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 #25
Source File: formatter.py    From pipenv with MIT License 5 votes vote down vote up
def report(vulns, full=False, json_report=False, bare_report=False, checked_packages=0, db=None, key=None):
    if bare_report:
        return BareReport.render(vulns, full=full)
    if json_report:
        return JsonReport.render(vulns, full=full)
    size = get_terminal_size()
    used_db = get_used_db(key=key, db=db)
    if size.columns >= 80:
        return SheetReport.render(vulns, full=full, checked_packages=checked_packages, used_db=used_db)
    return BasicReport.render(vulns, full=full, checked_packages=checked_packages, used_db=used_db) 
Example #26
Source File: formatter.py    From pipenv with MIT License 5 votes vote down vote up
def get_terminal_size():
        size = namedtuple("_", ["rows", "columns"])
        try:
            rows, columns = subprocess.check_output(
                ['stty', 'size'],
                stderr=subprocess.STDOUT
            ).split()
            return size(rows=int(rows), columns=int(columns))
        # this won't work
        # - on windows (FileNotFoundError/OSError)
        # - python 2.6 (AttributeError)
        # - if the output is somehow mangled (ValueError)
        except (ValueError, FileNotFoundError, OSError,
                AttributeError, subprocess.CalledProcessError):
            return size(rows=0, columns=0) 
Example #27
Source File: term.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def get_terminal_size(self):
        import shutil
        try:
            size = shutil.get_terminal_size()
            return size.lines, size.columns
        except AttributeError:
            screen = self._get_screen_info()
            window = screen.srWindow
            h = window.Bottom - window.Top
            w = window.Right - window.Left

            return h or 80, w or 25 
Example #28
Source File: term.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def width(self):
        return self.get_terminal_size()[1]-1 
Example #29
Source File: term.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def height(self):
        return self.get_terminal_size()[0]-1 
Example #30
Source File: compat.py    From deepWordBug with Apache License 2.0 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])