Python os.get_terminal_size() Examples

The following are 30 code examples of os.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 os , or try the search function .
Example #1
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main 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: console.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def fit(string, prefix: str = "    "):
    columns = os.get_terminal_size().columns
    output = ""
    for word in string.split(" "):
        if (len(output.split("\n")[-1]) >= (columns - 1)) or (len(output.split("\n")[-1] + word + " ") >= (columns - 1)):
            output += "\n" + prefix
        
        if len(word) > (columns - 1) - len(output.split("\n")[-1]):
            while word:
                index = (columns - 1) - len(output.split("\n")[-1])
                output += word[:index] + "\n" + prefix
                word = word[index:]
            output += " "
        else:
            output += word + " "
    return output 
Example #3
Source File: test_os.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_stty_match(self):
        """Check if stty returns the same results

        stty actually tests stdin, so get_terminal_size is invoked on
        stdin explicitly. If stty succeeded, then get_terminal_size()
        should work too.
        """
        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

        try:
            actual = os.get_terminal_size(sys.__stdin__.fileno())
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise
        self.assertEqual(expected, actual) 
Example #4
Source File: test_os.py    From ironpython3 with Apache License 2.0 6 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.
        """
        try:
            size = os.get_terminal_size()
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise

        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example #5
Source File: console.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def print(*messages, color: str = "white", dark: bool = False, prefix: str = "", parse: bool = True, **kwargs):
    if "file" not in kwargs:
        kwargs["file"] = stdout
    #try:
    columns = os.get_terminal_size().columns
    #except ValueError:
    #    columns = None
    string = ""
    for message in messages:
        if isinstance(message, (tuple, list, set)):
            if isinstance(message[-1], bool):
                *message, dark = message
            if message[-1] in termcolor.COLORS.keys():
                *message, color = message
            message = " ".join(map(str, message))
        string += termcolor.colored(message, color, attrs=["dark"] if dark else [])
    #if columns:
    _print((fit(string, prefix) if parse else string), **kwargs)
    #else:
    #    _print(string, **kwargs) 
Example #6
Source File: terminal.py    From ward with MIT License 6 votes vote down vote up
def output_dots_global(
    fail_limit: int, test_results_gen: Generator[TestResult, None, None]
) -> List[TestResult]:
    column = 0
    num_failures = 0
    all_results = []
    try:
        print()
        for result in test_results_gen:
            all_results.append(result)
            print_dot(result)
            column += 1
            if column == get_terminal_size().width:
                print()
                column = 0
            if result.outcome == TestOutcome.FAIL:
                num_failures += 1
            if num_failures == fail_limit:
                break
            sys.stdout.flush()
        print()
    except KeyboardInterrupt:
        output_run_cancelled()
    finally:
        return all_results 
Example #7
Source File: process.py    From selective_copy with MIT License 6 votes vote down vote up
def _show_progress_bar(self):
        """
        Print progress bar.
        :return: NoneType.
        """
        try:
            term_width = os.get_terminal_size(0)[0]
        except OSError:
            term_width = 80
        length = term_width - (len(str(self.total)) + 33)
        percent = round(100 * (self.processed / self.total))
        filled = int(length * self.processed // self.total)
        bar = f'|{"=" * filled}{"-" * (length - filled)}|' if term_width > 50 else ""
        suffix = (
            f"Files left: {self.total - self.processed} "
            if self.processed < self.total
            else "Done, log saved"
            if self.args.log
            else "Done           "
        )
        print(f"\rProgress: {bar} {percent}% {suffix}", end="\r", flush=True)
        if self.processed == self.total:
            print() 
Example #8
Source File: test_os.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

        stty actually tests stdin, so get_terminal_size is invoked on
        stdin explicitly. If stty succeeded, then get_terminal_size()
        should work too.
        """
        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

        try:
            actual = os.get_terminal_size(sys.__stdin__.fileno())
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise
        self.assertEqual(expected, actual) 
Example #9
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 6 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.
        """
        try:
            size = os.get_terminal_size()
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise

        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example #10
Source File: test_os.py    From Project-New-Reign---Nemesis-Main 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

        stty actually tests stdin, so get_terminal_size is invoked on
        stdin explicitly. If stty succeeded, then get_terminal_size()
        should work too.
        """
        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

        try:
            actual = os.get_terminal_size(sys.__stdin__.fileno())
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise
        self.assertEqual(expected, actual) 
Example #11
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 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.
        """
        try:
            size = os.get_terminal_size()
        except OSError as e:
            if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
                # Under win32 a generic OSError can be thrown if the
                # handle cannot be retrieved
                self.skipTest("failed to query terminal size")
            raise

        self.assertGreaterEqual(size.columns, 0)
        self.assertGreaterEqual(size.lines, 0) 
Example #12
Source File: progressBar.py    From metaknowledge with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, initPer, initString = ' ', output = sys.stdout, secondRow = False, dummy = False):
        self.dummy = dummy
        self.finished = False
        self.big = secondRow
        self.per = initPer
        self.out = output
        self.inputString = initString
        if not dummy:
            self.sTime = time.time()
            try:
                self.barMaxLength = os.get_terminal_size(self.out.fileno()).columns - self.difTermAndBar
                if self.barMaxLength < 0:
                    self.barMaxLength = 0
            except OSError:
                self.barMaxLength = 80 - self.difTermAndBar
            except AttributeError:
                #Pypy fallback
                self.barMaxLength = 80 - self.difTermAndBar
            self.ioThread = threading.Thread(target = self.threadedUpdate, kwargs = {"self" : self})
            self.ioThread.daemon = True
            self.ioThread.start() 
Example #13
Source File: progressBar.py    From metaknowledge with GNU General Public License v2.0 6 votes vote down vote up
def finish(self, inputString):
        if not self.dummy:
            self.finished = True
            self.inputString = str(inputString)
            self.ioThread.join()
            try:
                self.barMaxLength = os.get_terminal_size(self.out.fileno()).columns - self.difTermAndBar
                if self.barMaxLength < 0:
                    self.barMaxLength = 0
            except OSError:
                self.barMaxLength = 80 - self.difTermAndBar
            except AttributeError:
                #Pypy fallback
                self.barMaxLength = 80 - self.difTermAndBar
            if self.big:
                self.out.write('\n' + ' ' * (self.barMaxLength + self.difTermAndBar) + '\033[F')
            else:
                self.out.write('\r')
            if len(self.inputString) < self.barMaxLength + self.difTermAndBar - self.timeLength:
                tString = self.prepTime(time.time() - self.sTime, self.barMaxLength + self.difTermAndBar - len(self.inputString) - 1)
                self.out.write(self.inputString + ' ' + tString)
            else:
                self.out.write(self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength) + self.prepTime(time.time() - self.sTime, self.timeLength))
            self.out.write('\n')
            self.out.flush() 
Example #14
Source File: ls_open_file_handles.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def exit_handler(self):
		indent = '  > '
		terminal_width = os.get_terminal_size()[0]
		for fileref, path, trace in self.openfiles:
			if fileref() and fileref().closed and self.do_print_only_open:
				continue
			print("-" * terminal_width)
			print("  {} = {}".format('path', path))
			lines = ''.join(trace).splitlines()
			_updated_lines = []
			for l in lines:
				ul = textwrap.fill(l,
								   initial_indent=indent,
								   subsequent_indent=indent,
								   width=terminal_width)
				_updated_lines.append(ul)
			lines = _updated_lines
			print('\n'.join(lines))
			print("-" * terminal_width)
			print() 
Example #15
Source File: __init__.py    From PrettyErrors with MIT License 5 votes vote down vote up
def get_terminal_width(self):
        """Width of terminal in characters."""
        try:
            return os.get_terminal_size()[0]
        except Exception:
            return 79 
Example #16
Source File: terminal.py    From ward with MIT License 5 votes vote down vote up
def output_test_result_line(test_result: TestResult):
    colour = outcome_to_colour(test_result.outcome)
    bg = f"on_{colour}"
    padded_outcome = f" {test_result.outcome.name[:4]} "

    iter_indicator = format_test_case_number(test_result)
    mod_name = format_test_id(test_result)
    if (
        test_result.outcome == TestOutcome.SKIP
        or test_result.outcome == TestOutcome.XFAIL
    ):
        reason = test_result.test.marker.reason or ""
        if reason:
            reason = lightblack(f" [{reason}]")
    else:
        reason = ""

    name_or_desc = test_result.test.description
    indent = (
        len(padded_outcome)
        + len(test_result.test.module_name)
        + len(str(test_result.test.line_number))
        + len(iter_indicator)
        + 4
    )
    width = get_terminal_size().width - indent
    print(
        colored(padded_outcome, color="grey", on_color=bg),
        mod_name,
        multiline_description(name_or_desc + reason, indent=indent, width=width),
    ) 
Example #17
Source File: display.py    From Dirscaner with GNU General Public License v3.0 5 votes vote down vote up
def ProgressBar(requrl,counturl,Allurl):
	# time.sleep(1)

	sz = os.get_terminal_size()

	alllen = '[*] [{:.2%}'.format(counturl/len(Allurl)) + '| %d / %d]'%(counturl,len(Allurl))+'  Requesting:%s' %requrl
	barlen = sz.columns - len(alllen) - 1

	allbar = alllen +' '*barlen + '\r'
	sys.stdout.write(allbar)
	sys.stdout.flush() 
Example #18
Source File: terminal.py    From ward with MIT License 5 votes vote down vote up
def __init__(
        self,
        suite,
        test_output_style: str,
        config_path: Optional[Path],
        show_diff_symbols: bool = False,
    ):
        self.suite = suite
        self.test_output_style = test_output_style
        self.config_path = config_path
        self.show_diff_symbols = show_diff_symbols
        self.terminal_size = get_terminal_size() 
Example #19
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api)) 
Example #20
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def _safe_get_terminal_size():
    try:
        return os.get_terminal_size()
    except Exception:
        return None 
Example #21
Source File: terminal.py    From ward with MIT License 5 votes vote down vote up
def get_terminal_size() -> TerminalSize:
    for i in range(0, 3):
        try:
            cols, rows = os.get_terminal_size(i)
            return TerminalSize(height=rows, width=cols)
        except OSError:
            continue
    return TerminalSize(height=24, width=80) 
Example #22
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_os_environ_first(self):
        "Check if environment variables have precedence"

        with support.EnvironmentVarGuard() as env:
            env['COLUMNS'] = '777'
            del env['LINES']
            size = shutil.get_terminal_size()
        self.assertEqual(size.columns, 777)

        with support.EnvironmentVarGuard() as env:
            del env['COLUMNS']
            env['LINES'] = '888'
            size = shutil.get_terminal_size()
        self.assertEqual(size.lines, 888) 
Example #23
Source File: log.py    From Minipolish with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: humanize.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format_in_columns(elements, total_width=None, sep="  ", indent="  ", min_height=10):
    """
    >>> print(format_in_columns([str(i) for i in range(100)], 50))
      0  10  20  30  40  50  60  70  80  90
      1  11  21  31  41  51  61  71  81  91
      2  12  22  32  42  52  62  72  82  92
      3  13  23  33  43  53  63  73  83  93
      4  14  24  34  44  54  64  74  84  94
      5  15  25  35  45  55  65  75  85  95
      6  16  26  36  46  56  66  76  86  96
      7  17  27  37  47  57  67  77  87  97
      8  18  28  38  48  58  68  78  88  98
      9  19  29  39  49  59  69  79  89  99
    """

    if not total_width:
        try:
            total_width, _ = os.get_terminal_size()
        except:
            total_width = 80

    widest = min(max(len(k) for k in elements), total_width)
    columns = max((total_width - len(indent)) // (widest + len(sep)), 1)
    height = max(min_height, (len(elements) // columns) + 1)

    # arrange the elements in columns
    columns = [[elem for (__, elem) in group]
               for __, group in itertools.groupby(enumerate(elements), lambda p: p[0]//height)]
    rows = itertools.zip_longest(*columns)

    col_max = total_width - len(sep) * (len(columns) - 1)
    column_lens = [min(max(map(len, column)), col_max) for column in columns]

    return '\n'.join(indent + sep.join([(string or "").ljust(column_lens[column_num])
                                        for column_num, string in enumerate(row)])
                     for row in rows) 
Example #25
Source File: logging.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_width(TERM_WIDTH):
    if TERM_WIDTH in (True, None):
        TERM_WIDTH, _ = os.get_terminal_size()
        TERM_WIDTH = max(TERM_WIDTH, 120)
    if TERM_WIDTH:
        compact = lambda line: _compact(line, TERM_WIDTH-5)
    else:
        TERM_WIDTH = 0
        compact = lambda line: line
    globals().update(locals()) 
Example #26
Source File: display.py    From pyShelf with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.term = True
        self.w, self.y = os.get_terminal_size()[0], os.get_terminal_size()[1]
        self.home = os.environ["HOME"]
        try:
            self.user = os.environ["USER"]
        except KeyError:
            self.user = None
        self.version = "0.4.0"
        self.slogan = "The Installer Initiative"
        self.green = "\033[1;32m"
        self.blue = "\033[94m"
        self.clr_term = "\033[m" 
Example #27
Source File: __init__.py    From code with MIT License 5 votes vote down vote up
def stderr_width():
    global _stderr_width
    if _stderr_width is None:
        if stderr_tty() and hasattr(os, "get_terminal_size"):
            _stderr_width = os.get_terminal_size(sys.stderr.fileno()).columns
        else:
            _stderr_width = 80
    return _stderr_width 
Example #28
Source File: __init__.py    From code with MIT License 5 votes vote down vote up
def _handle_sigwinch(signum, stack):
    global _stderr_width
    if stderr_tty() and hasattr(os, "get_terminal_size"):
        _stderr_width = os.get_terminal_size(sys.stderr.fileno()).columns 
Example #29
Source File: progressBar.py    From metaknowledge with GNU General Public License v2.0 5 votes vote down vote up
def threadedUpdate(self = None):
        while not self.finished:
            try:
                self.barMaxLength = os.get_terminal_size(self.out.fileno()).columns - self.difTermAndBar
                if self.barMaxLength < 0:
                    self.barMaxLength = 0
            except OSError:
                self.barMaxLength = 80 - self.difTermAndBar
            except AttributeError:
                #Pypy fallback
                self.barMaxLength = 80 - self.difTermAndBar
            self.out.write('\r')
            percentString = '{:.1%}'.format(self.per).rjust(self.percLength, ' ')
            barLength = int(self.per * self.barMaxLength)
            if self.big and self.inputString:
                self.dString = self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength) + self.prepTime(time.time() - self.sTime, self.timeLength)
                if barLength >= self.barMaxLength:
                    self.out.write('[' + '=' * barLength + ']' + percentString)
                    self.out.write('\n' + self.dString + '\033[F')
                else:
                    self.out.write('[' + '=' * barLength + '>' + ' ' * (self.barMaxLength - barLength - 1) + ']' + percentString)
                    self.out.write('\n' + self.dString + '\033[')
            elif self.inputString:
                self.dString = self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength - self.percLength - 2) + '[' + self.prepTime(time.time() - self.sTime, self.timeLength) +  ']' + percentString
                self.out.write(self.dString)
            else:
                if barLength >= self.barMaxLength:
                    self.out.write('[' + '=' * barLength + ']' + percentString + '\r')
                else:
                    self.out.write('[' + '=' * barLength + '>' + ' ' * (self.barMaxLength - barLength - 1) + ']' + percentString + '\r')
            self.out.flush()
            time.sleep(.1) 
Example #30
Source File: terminal.py    From aptsources-cleanup with MIT License 5 votes vote down vote up
def _refresh_width_impl(file):
		return file.isatty() and os.get_terminal_size(file.fileno()).columns