当前位置: 首页>>代码示例>>Python>>正文


Python os.get_terminal_size方法代码示例

本文整理汇总了Python中os.get_terminal_size方法的典型用法代码示例。如果您正苦于以下问题:Python os.get_terminal_size方法的具体用法?Python os.get_terminal_size怎么用?Python os.get_terminal_size使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.get_terminal_size方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_does_not_crash

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_os.py

示例2: exit_handler

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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() 
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:22,代码来源:ls_open_file_handles.py

示例3: test_stty_match

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:24,代码来源:test_os.py

示例4: fit

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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 
开发者ID:black-security,项目名称:cyber-security-framework,代码行数:18,代码来源:console.py

示例5: print

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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) 
开发者ID:black-security,项目名称:cyber-security-framework,代码行数:22,代码来源:console.py

示例6: test_stty_match

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:21,代码来源:test_shutil.py

示例7: output_dots_global

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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 
开发者ID:darrenburns,项目名称:ward,代码行数:27,代码来源:terminal.py

示例8: _show_progress_bar

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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() 
开发者ID:pltnk,项目名称:selective_copy,代码行数:25,代码来源:process.py

示例9: __init__

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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() 
开发者ID:UWNETLAB,项目名称:metaknowledge,代码行数:23,代码来源:progressBar.py

示例10: finish

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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() 
开发者ID:UWNETLAB,项目名称:metaknowledge,代码行数:27,代码来源:progressBar.py

示例11: get_terminal_size

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
def get_terminal_size():
    try:
        return os.get_terminal_size().columns
    except:
        return 50 
开发者ID:kevink1103,项目名称:pyprnt,代码行数:7,代码来源:util.py

示例12: get_terminal_size_stderr

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
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 
开发者ID:rrwick,项目名称:Rebaler,代码行数:11,代码来源:log.py

示例13: pretty_table_printer

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
def pretty_table_printer(dataset_or_ins) -> PrettyTable:
    r"""
    :param dataset_or_ins: 传入一个dataSet或者instance
    ins = Instance(field_1=[1, 1, 1], field_2=[2, 2, 2], field_3=["a", "b", "c"])
    +-----------+-----------+-----------------+
    |  field_1  |  field_2  |     field_3     |
    +-----------+-----------+-----------------+
    | [1, 1, 1] | [2, 2, 2] | ['a', 'b', 'c'] |
    +-----------+-----------+-----------------+
    :return: 以 pretty table的形式返回根据terminal大小进行自动截断
    """
    x = PrettyTable()
    try:
        sz = os.get_terminal_size()
        column = sz.columns
        row = sz.lines
    except OSError:
        column = 144
        row = 11

    if type(dataset_or_ins).__name__ == "DataSet":
        x.field_names = list(dataset_or_ins.field_arrays.keys())
        c_size = len(x.field_names)
        for ins in dataset_or_ins:
            x.add_row([sub_column(ins[k], column, c_size, k) for k in x.field_names])
            row -= 1
            if row < 0:
                x.add_row(["..." for _ in range(c_size)])
                break
    elif type(dataset_or_ins).__name__ == "Instance":
        x.field_names = list(dataset_or_ins.fields.keys())
        c_size = len(x.field_names)
        x.add_row([sub_column(dataset_or_ins[k], column, c_size, k) for k in x.field_names])

    else:
        raise Exception("only accept  DataSet and Instance")
    x.align = "l"

    return x 
开发者ID:fastnlp,项目名称:fastNLP,代码行数:41,代码来源:utils.py

示例14: terminal_width

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
def terminal_width(stdout):
    if hasattr(os, 'get_terminal_size'):
        # python 3.3 onwards has built-in support for getting terminal size
        try:
            return os.get_terminal_size().columns
        except OSError:
            return None

    if sys.platform == 'win32':
        return _get_terminal_width_windows(stdout)
    else:
        return _get_terminal_width_ioctl(stdout) 
开发者ID:openstack,项目名称:cliff,代码行数:14,代码来源:utils.py

示例15: exit_if_terminal_size_is_to_small

# 需要导入模块: import os [as 别名]
# 或者: from os import get_terminal_size [as 别名]
def exit_if_terminal_size_is_to_small(self):
        # get_terminal_size is introduced in python 3.3
        try:
            (columns, lines) = os.get_terminal_size()
        except AttributeError:
            return

        if columns < 99 and lines < 30:
            msg = '\n Terminal window screen must be at least 99x30\n'
            msg += ' Your size: %sx%s \n'

            sys.exit(msg % (columns, lines)) 
开发者ID:bjarneo,项目名称:Pytify,代码行数:14,代码来源:song_list.py


注:本文中的os.get_terminal_size方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。