def get_terminal_size(defaultx=80, defaulty=25):
return _get_terminal_size((defaultx, defaulty))
python类get_terminal_size()的实例源码
def get_terminal_size():
size = namedtuple("_", ["rows", "columns"])
try:
rows, columns = subprocess.check_output(
['stty', 'size'],
stderr=subprocess.STDOUT
).split()
return size(rows=int(rows), columns=int(columns))
# this won't work
# - on windows (FileNotFoundError/OSError)
# - python 2.6 (AttributeError)
# - if the output is somehow mangled (ValueError)
except (ValueError, FileNotFoundError, OSError,
AttributeError, subprocess.CalledProcessError):
return size(rows=0, columns=0)
def report(vulns, full=False, json_report=False, bare_report=False, checked_packages=0, db=None, key=None):
if bare_report:
return BareReport.render(vulns, full=full)
if json_report:
return JsonReport.render(vulns, full=full)
size = get_terminal_size()
used_db = get_used_db(key=key, db=db)
if size.columns >= 80:
return SheetReport.render(vulns, full=full, checked_packages=checked_packages, used_db=used_db)
return BasicReport.render(vulns, full=full, checked_packages=checked_packages, used_db=used_db)
def expand(lines, indent=4, maxwidth=100):
"""Expand all tabstops (\t) in each line intelligently
"Intelligently" means that consecutive lines with the same amount of '\t'
characters are treated like a table, giving each column the same space.
Return `lines` with all tabs expanded
"""
width = min(get_terminal_size()[0], maxwidth)
expanded = []
for section in _split_sections(_explode(lines, indent)):
widths = _col_widths(section)
for line in section:
expanded.append(_join_line(line, widths, width))
return expanded
def _width(self) -> int:
"""Get the number of columns to wrap text to.
This is either the width of the terminal window or the maximum width
set in the Formatter instance, whichever is smaller.
"""
if self.formatter.auto_width:
return min(
self.formatter.max_width, shutil.get_terminal_size().columns)
else:
return self.formatter.max_width
def get_terminal_size():
size = get_terminal_dimensions((120, 40))
return TerminalSize(size.columns, size.lines)
def __init__(self, lifecycle, stop_event, *args):
self.lifecycle = lifecycle
self.stop_event = stop_event
self.last_size = get_terminal_size()
self.should_run = True
super(ResizeChecker, self).__init__()
def run(self):
logger.debug('ResizeChecker started')
while not self.stop_event.wait(self.CHECK_INTERVAL):
new_size = get_terminal_size()
if self.last_size != get_terminal_size():
logger.debug('Terminal size changed to %s' % (new_size, ))
self.lifecycle.player.trigger_redraw()
self.last_size = new_size
def __init__(self, prog):
terminal_width = shutil.get_terminal_size().columns
os.environ['COLUMNS'] = str(terminal_width)
max_help_position = min(max(24, terminal_width // 3), 40)
super().__init__(prog, max_help_position=max_help_position)
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.
"""
size = shutil.get_terminal_size()
self.assertGreaterEqual(size.columns, 0)
self.assertGreaterEqual(size.lines, 0)
def test_os_environ_first(self):
"Check if environment variables have precedence"
with support.EnvironmentVarGuard() as env:
env['COLUMNS'] = '777'
size = shutil.get_terminal_size()
self.assertEqual(size.columns, 777)
with support.EnvironmentVarGuard() as env:
env['LINES'] = '888'
size = shutil.get_terminal_size()
self.assertEqual(size.lines, 888)
def _pretty_wrap(text, pretext, *, width=-1):
if width is None:
return pretext + text
elif width == -1:
width = shutil.get_terminal_size().columns
l1, *lx = textwrap.wrap(text, width=width - 1 - len(pretext))
lx = [((' ' * len(pretext)) + l).rstrip().ljust(width) for l in lx]
l1 = (pretext + l1).ljust(width)
return ''.join([l1, *lx])
def __del__(self):
if self.draw:
print(' ' * (get_terminal_size().columns-1), end='\r')
def _pprint_meter(self, perc, *, char='#', text='', shift=True):
tx, ty = get_terminal_size()
if shift:
outstr = text + "{}".format(char * (int((tx - len(text)) * perc) - 1))
else:
outstr = text + "{}".format(char * (int(tx * perc) - 1))[len(text):]
print(outstr.ljust(tx - 1), end='\r')
def _pretty_wrap(text, pretext, *, width=-1):
if width is None:
return pretext + text
elif width == -1:
width = shutil.get_terminal_size().columns
l1, *lx = textwrap.wrap(text, width=width - 1 - len(pretext))
lx = [((' ' * len(pretext)) + l).rstrip().ljust(width) for l in lx]
l1 = (pretext + l1).ljust(width)
return ''.join([l1, *lx])
def callback(parser):
@ivy.hooks.register('main')
def tree_callback():
if not ivy.site.home():
sys.exit("Error: cannot locate the site's home directory.")
cols, _ = shutil.get_terminal_size()
print('?' * cols)
print('Site: %s' % ivy.site.home())
print('?' * cols)
print(ivy.nodes.root().str())
print('?' * cols)
def get_available_screen_for_user_agent():
""" Get the available length for the user agent """
column_padding = 18
avail_length = 0
for c in Client.query.all():
columns_length = len(str(c.id)) + len(str(c.client_id)) + len(str(c.last_beaconed)) + len(str(c.ip))
current_avail_length = shutil.get_terminal_size().columns - columns_length - column_padding
avail_length = max(avail_length, current_avail_length)
return avail_length
def __init__(self, num_lines=shutil.get_terminal_size().lines):
self.num_lines = num_lines
def _size_36():
""" returns the rows, columns of terminal """
from shutil import get_terminal_size
dim = get_terminal_size()
if isinstance(dim, list):
return dim[0], dim[1]
return dim.lines, dim.columns
def print_command(self, keyword, description, max_len, out_stream):
keyword_column = ('{0: <%s} ' % max_len).format(keyword)
if six.PY3:
width = shutil.get_terminal_size().columns or 80
else:
width = 80
output = textwrap.fill(description, width=width, initial_indent=keyword_column, subsequent_indent=' '*(max_len+2))
print(output, file=out_stream)