本文整理匯總了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)
示例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()
示例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)
示例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
示例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)
示例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)
示例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
示例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()
示例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()
示例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()
示例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
示例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
示例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
示例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)
示例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))