def get_terminal_size(self): fallback = (80, 24) try: from shutil import get_terminal_size except ImportError: try: import termios import fcntl import struct fd = self.stdout.fileno() call = fcntl.ioctl(fd, 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: # We are not going to care about the os environment variable # of LINES and COLUMNS because it refers to the wrong tty try: size = os.get_terminal_size(self.stdout.fileno()) except (AttributeError, ValueError, OSError): # stdout is None, closed, detached, or not a terminal, or # os.get_terminal_size() is unsupported size = os.terminal_size(fallback) columns = size.columns lines = size.lines return os.terminal_size((columns, lines))
def get_size(): """ Returns the terminal size. Like `shutil.get_terminal_size()`, but works better. Honors the COLUMNS and LINES environment variables, if set. Otherwise, uses `_determine_size()`. """ try: columns = int(os.environ['COLUMNS']) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ['LINES']) except (KeyError, ValueError): lines = 0 if columns <= 0 or lines <= 0: try: size = _determine_size() except (NameError, OSError): size = os.terminal_size(fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return os.terminal_size((columns, lines))
def container_exec(cmd, resource_group_name, name, exec_command, container_name=None): """Start exec for a container. """ container_client = cf_container(cmd.cli_ctx) container_group_client = cf_container_groups(cmd.cli_ctx) container_group = container_group_client.get(resource_group_name, name) if container_name or container_name is None and len(container_group.containers) == 1: # If only one container in container group, use that container. if container_name is None: container_name = container_group.containers[0].name try: terminalsize = os.get_terminal_size() except OSError: terminalsize = os.terminal_size((80, 24)) terminal_size = ContainerExecRequestTerminalSize(rows=terminalsize.lines, cols=terminalsize.columns) exec_request = ContainerExecRequest(command=exec_command, terminal_size=terminal_size) execContainerResponse = container_client.execute_command(resource_group_name, name, container_name, exec_request) if platform.system() is WINDOWS_NAME: _start_exec_pipe_windows(execContainerResponse.web_socket_uri, execContainerResponse.password) else: _start_exec_pipe_linux(execContainerResponse.web_socket_uri, execContainerResponse.password) else: raise CLIError('--container-name required when container group has more than one container.')
def get_terminal_size(fallback=(80, 24)): """Look up character width of terminal.""" try: return shutil.get_terminal_size(fallback) except Exception: # pragma: no cover return os.terminal_size(fallback)
def get_terminal_size(): from shutil import get_terminal_size as t_size # get_terminal_size can report 0, 0 if run from pseudo-terminal prior Python 3.11 versions columns = t_size().columns or 80 lines = t_size().lines or 24 return os.terminal_size((columns, lines))
def test_get_terminal_size_in_pty_defaults_to_80(self) -> None: # when run using a pty, `os.get_terminal_size()` returns `0, 0` ret = os.terminal_size((0, 0)) mock_environ = os.environ.copy() mock_environ.pop('COLUMNS', None) with mock.patch.object(os, 'get_terminal_size', return_value=ret): with mock.patch.dict(os.environ, values=mock_environ, clear=True): assert get_terminal_width() == 80
def test_get_terminal_size(self, mock_os): ts = os.terminal_size((10, 5)) mock_os.get_terminal_size.return_value = ts width = utils.terminal_width(sys.stdout) self.assertEqual(10, width) mock_os.get_terminal_size.side_effect = OSError() width = utils.terminal_width(sys.stdout) self.assertIs(None, width)
def prepare_for_output(monkeypatch): # terminal size affects output display so force a consistent size monkeypatch.setattr( "shutil.get_terminal_size", lambda *args, **kwargs: os.terminal_size((1000, 1000)), ) # raise an exception instead of exiting (or attempting to call func() with missing args) monkeypatch.setattr("argparse._sys.exit", raise_an_exception)
def get_terminal_size_stderr(fallback=(80, 24)): """ Unlike shutil.get_terminal_size, which looks at stdout, this looks at stderr. """ try: size = os.get_terminal_size(sys.__stderr__.fileno()) except (AttributeError, ValueError, OSError): size = os.terminal_size(fallback) return size
def get_terminal_size(fallback=(80, 24)): """Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # columns, lines are the working values try: columns = int(os.environ['COLUMNS']) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ['LINES']) except (KeyError, ValueError): lines = 0 # only query if necessary if columns <= 0 or lines <= 0: try: size = os.get_terminal_size(sys.__stdout__.fileno()) except (AttributeError, ValueError, OSError): # stdout is None, closed, detached, or not a terminal, or # os.get_terminal_size() is unsupported size = os.terminal_size(fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return os.terminal_size((columns, lines))
def get_terminal_size(fallback=(80, 24)): try: columns = int(os.environ['COLUMNS']) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ['LINES']) except (KeyError, ValueError): lines = 0 if columns <= 0 or lines <= 0: try: size = os.get_terminal_size(sys.__stdout__.fileno()) except (NameError, OSError): size = os.terminal_size(fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return os.terminal_size((columns, lines))
def printer(monkeypatch, request): def fin(): """Ensure that the cursor is shown when printer unit tests complete.""" print(ansi.SHOW_CURSOR, end='', flush=True) request.addfinalizer(fin) monkeypatch.setattr('shutil.get_terminal_size', lambda: os.terminal_size( (80, 24))) return Printer()
def test_echo_with_pager_if_needed_u(mock_click, mock_shutil_get_terminal_size, columns, rows, output, uses_pager): mock_shutil_get_terminal_size.return_value = os.terminal_size( [columns, rows]) echo.echo_with_pager_if_needed(output) if uses_pager: assert mock_click.mock_calls == [mock.call.echo_via_pager(output)] else: assert mock_click.mock_calls == [mock.call.echo(output)]
def test_utils_terminal_width_get_terminal_size(mock_os): if not hasattr(os, 'get_terminal_size'): raise nose.SkipTest('only needed for python 3.3 onwards') ts = os.terminal_size((10, 5)) mock_os.get_terminal_size.return_value = ts width = utils.terminal_width(sys.stdout) assert width == 10 mock_os.get_terminal_size.side_effect = OSError() width = utils.terminal_width(sys.stdout) assert width is None
def test_page(self, mockShutil: Mock, mockPager: Mock) -> None: cols: int = 80 rows: int = 24 mockShutil.get_terminal_size.return_value = os.terminal_size( (cols, rows)) lines: List[str] = [ "This is the first line.", "this is the second line.", "123456789 " * 10, "123\n567\n9 " * 10, "This is the third and final line.", ] lines = "\n".join(lines).splitlines() utils.page(lines) text: str = "\n".join( textwrap.fill(line.strip(), cols - 1) for line in lines) mockPager.assert_called_once_with(text)
def build_sizer(fd: Optional[Union[TextIO, int]] = None) -> Callable: """ Build a function returning the terminal size depending on the available and requested I/O streams. Try to get the terminal size of the given io stream, otherwise defaults to stdin, and if stdin is no tty, defaults to a fixed size of (80, 24). """ if fd is None: if os.isatty(0): return partial(os.get_terminal_size, 0) else: if isinstance(fd, TextIO): fd = fd.fileno() if type(fd) is int: if is_suitable_io_device(fd): return partial(os.get_terminal_size, fd) return partial(os.get_terminal_size, 0) return lambda: os.terminal_size((80, 24))
def test_show_list_tools_long_ifw(capsys, monkeypatch, columns, expect): update_xml = (Path(__file__).parent / "data" / "mac-desktop-tools_ifw-update.xml").read_text("utf-8") monkeypatch.setattr(MetadataFactory, "fetch_http", lambda self, _: update_xml) monkeypatch.setattr(shutil, "get_terminal_size", lambda fallback: os.terminal_size((columns, 24))) meta = MetadataFactory( ArchiveId("tools", "mac", "desktop"), tool_name="tools_ifw", is_long_listing=True, ) show_list(meta) out, err = capsys.readouterr() sys.stdout.write(out) sys.stderr.write(err) assert out == expect
def pager_process(pagercmd, stdout=None, stderr=None): if stdout is None: stdout = sys.stdout if stderr is None: stderr = sys.stderr # When running interactively `less` does not handle window resizes # unless we explicitly hardcode the new term size into the env. There # is currently a bug in docker for mac that sometimes breaks this test. env = os.environ.copy() termsize = shutil.get_terminal_size() if 0 in termsize: warnings.warn("Could not determine terminal size") termsize = os.terminal_size((80, 24)) env['COLUMNS'] = str(termsize.columns) env['LINES'] = str(termsize.lines) return subprocess.Popen(pagercmd, shell=True, universal_newlines=True, bufsize=1, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, env=env)
import os sz = os.get_terminal_size() print(sz) print(sz.columns) print(sz.lines) sz = os.terminal_size((50, 24))
if record.levelno >= logging.CRITICAL: return self.critical_seq + msg + self.reset_all_seq elif record.levelno >= logging.ERROR: return self.error_seq + msg + self.reset_all_seq elif record.levelno >= logging.WARNING: return self.warning_seq + msg + self.reset_all_seq elif record.levelno >= STATUS: return self.status_seq + msg + self.reset_all_seq elif record.levelno >= MESSAGE: return self.message_seq + msg + self.reset_all_seq return msg _last_term_sz = os.terminal_size((80, 24)) def get_term_sz() -> os.terminal_size: global _last_term_sz # pylint: disable=C0103,W0603 _last_term_sz = shutil.get_terminal_size(_last_term_sz) return _last_term_sz class PrettyPrinter(_pprinter): def __init__( self, *args, # noqa: ANN002 indent: int = 2, width: Optional[int] = None,
# 13.5. Getting the Terminal Size import os sz = os.get_terminal_size() # OSError: [WinError 6] 句柄无效。 print(sz) os.terminal_size(columns=80, lines=24) print(sz.columns) print(sz.lines)
def get_terminal_size(fallback=(80, 24)): try: return shutil.get_terminal_size(fallback) except Exception: # pragma: no cover return os.terminal_size(fallback)
def test_get_terminal_size_in_pty_defaults_to_80(self) -> None: # when run using a pty, `os.get_terminal_size()` returns `0, 0` ret = os.terminal_size((0, 0)) with mock.patch.object(os, 'get_terminal_size', return_value=ret): assert get_terminal_width() == 80
def replacement(fallback=None): columns, lines = shutil.original_get_terminal_size(fallback) # One fewer column so that full-width progress bar doesn't flow # onto the next line. return os.terminal_size((columns - 1, lines))
def mock_shutil_get_terminal_size(): fake_terminal = os.terminal_size([80, 24]) with mock.patch("snapcraft_legacy.cli.echo.shutil.get_terminal_size", return_value=fake_terminal) as mock_terminal_size: yield mock_terminal_size
def get_terminal_size(fallback=(80, 24)): return os.terminal_size(fallback)
def fake_terminal_size(*args, **kwargs): return os.terminal_size(PREDEFINED_TERMINAL_SIZE)
parser.error('%s does not exist or no permissions or not executable' % parsed.nvidia_settings_path) if not os.path.isfile(parsed.xterm_path) or not os.access( parsed.xterm_path, os.X_OK): parser.error('%s does not exist or no permissions or not executable' % parsed.xterm_path) parsed.context_path = parsed.context_path.rstrip('/') return parsed if __name__ == '__main__': name = 'nvidia-settings-rest-api' version = '0.0.1' config = cli_args(description='%s-%s' % (name, version)) configure_root_logger(level=logging.DEBUG) set_process_name('name', 'version', config_obj=config) os.terminal_size((500, 20)) api = Api(config=config, name=name, version=version) aiohttp.web.run_app( api.app, host=api.config.bind, port=api.config.port, )
def _patched_get_terminal_size(fd=None): return os.terminal_size((80, 30))