當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。