本文整理汇总了Python中shutil.get_terminal_size函数的典型用法代码示例。如果您正苦于以下问题:Python get_terminal_size函数的具体用法?Python get_terminal_size怎么用?Python get_terminal_size使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_terminal_size函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, title='', label_text='', default='', padding=10, completer=None):
self.future = Future()
def accept_text(buf):
get_app().layout.focus(ok_button)
buf.complete_state = None
return True
def accept():
self.future.set_result(self.text_area.text)
def cancel():
self.future.set_result(None)
self.text_area = TextArea(
completer=completer,
text=default,
multiline=False,
width=D(preferred=shutil.get_terminal_size()[0]-padding),
accept_handler=accept_text)
ok_button = Button(text='OK', handler=accept)
cancel_button = Button(text='Cancel', handler=cancel)
self.dialog = Dialog(
title=title,
body=HSplit([
Label(text=label_text),
self.text_area
]),
buttons=[ok_button, cancel_button],
# buttons=[ok_button],
width=D(preferred=shutil.get_terminal_size()[0]-10),
modal=True)
开发者ID:dagraham,项目名称:etm-mv,代码行数:34,代码来源:view.py
示例2: internetFullStatusReport
def internetFullStatusReport(timeoutLimit = 5, whiptail = False, returnStatus = False):
"""
Full check of all sites used by PiNet. Only needed on initial install
"""
sites = []
sites.append([_("Main Raspbian repository"), "http://archive.raspbian.org/raspbian.public.key", ("Critical"), False])
sites.append([_("Raspberry Pi Foundation repository"), "http://archive.raspberrypi.org/debian/raspberrypi.gpg.key", ("Critical"),False])
sites.append([_("Github"), "https://github.com", ("Critical"), False])
sites.append([_("Bit.ly"), "http://bit.ly", ("Highly recommended"), False])
sites.append([_("Bitbucket (Github mirror, not active yet)"), "https://bitbucket.org", ("Recommended"), False])
sites.append([_("BlueJ"), "http://bluej.org", ("Recommended"), False])
sites.append([_("PiNet metrics"), "https://secure.pinet.org.uk", ("Recommended"), False])
for website in range(0, len(sites)):
sites[website][3] = testSiteConnection(sites[website][1])
if returnStatus:
return sites
if whiptail:
message = ""
for website in sites:
if sites[3]:
status = "Success"
else:
status = "Failed"
message = message + status + " - " + website[2] + " - " + website[0] + " (" + website[1] + ")\n"
if (shutil.get_terminal_size()[0] < 105) or (shutil.get_terminal_size()[0] < 30):
print("\x1b[8;30;105t")
time.sleep(0.05)
whiptailBox("msgbox", "Web filtering test results", message, True, height="14", width="100")
else:
for website in range(0, len(sites)):
print(str(sites[website][2] + " - " ))
开发者ID:jrobinson-uk,项目名称:PiNet,代码行数:31,代码来源:pinet-functions-python.py
示例3: _print_frame
def _print_frame(self, index):
self.frame_number = index
frame_text = '{color}Frame #{0:04d} of {1:d} :{nocolor}\n{2:s}\n'.format(
self.frame_number + 1, self._jury_state_count(),
self.painter_factory(self.game_controller.get_players())
.ascii_paint(
self.game_controller.jury_states[index]),
color=Fore.YELLOW + Style.BRIGHT,
nocolor=Fore.RESET + Style.NORMAL)
self.lock.acquire()
_clear()
height = get_terminal_size()[1] - 3
frame_text = frame_text.split('\n')
lines = len(frame_text)
frame_text = '\n\r'.join(frame_text[:height])
print(frame_text)
self.lock.release()
self.prev_frame = frame_text.split('\n')
if lines > get_terminal_size()[1]:
#print('')
clear_string(height + 1)
clear_string(height + 3)
self._error('Increase the height of the terminal and necessarily \
press Home to see the full information', end='')
clear_string(height + 2)
开发者ID:dimatomp,项目名称:play,代码行数:25,代码来源:ascii_visualizer.py
示例4: sigwinch_handler
def sigwinch_handler(self, n, frame):
self.window_height = shutil.get_terminal_size().lines - 10
self.window_width = shutil.get_terminal_size().columns - 20
curses.endwin()
self.stdscr.clear()
self.stdscr = curses.initscr()
self.win = curses.newwin(
5 + self.window_height,
self.window_width,
2,
4
)
开发者ID:Faedrivin,项目名称:StudDP,代码行数:12,代码来源:picker.py
示例5: test_os_environ_first
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)
开发者ID:Naddiseo,项目名称:cpython,代码行数:12,代码来源:test_shutil.py
示例6: __init__
def __init__(self, menu_items=[], title="", arrow="==>",
footer="Space = toggle ─ Enter = accept ─ q = cancel",
more="...", char_selected="[X]", char_empty="[ ]"):
"""Initialization.
Parameters
----------
menu_items : list
The data that will be used to create the menu items.
title : str, optional
A title to use on the menu.
arrow : str, optional
The character/s used to *point* the menu item that can be selected.
footer : str, optional
Informational text placed at the bottom of the menu.
more : str, optional
Character/s representing the availability of more menu items than the screen can display.
char_selected : str, optional
The character/s used to represent a selected menu item.
char_empty : str, optional
The character/s used to represent a non selected menu item.
"""
self.title = title
self.arrow = arrow
self.footer = footer
self.more = more
self.char_selected = char_selected
self.char_empty = char_empty
self.all_menu_items = []
self.win = None
self.stdscr = None
self.cursor = 0
self.offset = 0
self.selected = 0
self.selcount = 0
self.aborted = False
self.window_height = (get_terminal_size((80, 24))[1] or 24) - 5
self.window_width = (get_terminal_size((80, 24))[0] or 80)
self.length = 0
for item in menu_items:
self.all_menu_items.append({
"label": item,
"selected": False
})
self.length = len(self.all_menu_items)
self.curses_start()
curses.wrapper(self.curses_loop)
self.curses_stop()
开发者ID:Odyseus,项目名称:CinnamonTools,代码行数:51,代码来源:multi_select.py
示例7: installSoftwareList
def installSoftwareList(holdOffInstall = False):
"""
Replacement for ExtraSoftware function in bash.
Builds a list of possible software to install (using softwarePackage class) then displays the list using checkbox Whiptail menu.
Checks what options the user has collected, then saves the packages list to file (using pickle). If holdOffInstall is False, then runs installSoftwareFromFile().
"""
software = []
software.append(softwarePackage("Libreoffice", _("A free office suite, similar to Microsoft office"), "script", ["apt-get purge -y openjdk-6-jre-headless openjdk-7-jre-headless ca-certificates-java", "apt-get install -y libreoffice gcj-4.7-jre gcj-jre gcj-jre-headless libgcj13-awt"]))
software.append(softwarePackage("Arduino-IDE", _("Programming environment for Arduino microcontrollers"), "apt", ["arduino",]))
software.append(softwarePackage("Scratch-gpio", _("A special version of scratch for GPIO work") , "scratchGPIO", ["",]))
software.append(softwarePackage("Python-hardware", _("Python libraries for a number of additional addon boards"), "pip", ["pibrella skywriter unicornhat piglow pianohat explorerhat microstacknode twython"]))
software.append(softwarePackage("Epoptes", _("Free and open source classroom management software"), "epoptes", ["",]))
software.append(softwarePackage("BlueJ", _("A Java IDE for developing programs quickly and easily"), "script", ["rm -rf /tmp/bluej-314a.deb", "rm -rf /opt/ltsp/armhf/tmp/bluej-314a.deb", "wget http://bluej.org/download/files/bluej-314a.deb -O /tmp/bluej-314a.deb", "dpkg -i /tmp/bluej-314a.deb"]))
software.append(softwarePackage("Custom-package", _("Allows you to enter the name of a package from Raspbian repository"), "customApt", ["",]))
software.append(softwarePackage("Custom-python", _("Allows you to enter the name of a Python library from pip."), "customPip", ["",]))
softwareList = []
for i in software:
softwareList.append([i.name, i.description])
done = False
if (shutil.get_terminal_size()[0] < 105) or (shutil.get_terminal_size()[0] < 30):
print("\x1b[8;30;105t")
time.sleep(0.05)
#print("Resizing")
while done == False:
whiptailBox("msgbox", _("Additional Software"), _("In the next window you can select additional software you wish to install. Use space bar to select applications and hit enter when you are finished."), False)
result = (whiptailCheckList(_("Extra Software Submenu"), _("Select any software you want to install. Use space bar to select then enter to continue."), softwareList))
try:
result = result.decode("utf-8")
except AttributeError:
return
result = result.replace('"', '')
if result != "Cancel":
if result == "":
yesno = whiptailBox("yesno", _("Are you sure?"), _("Are you sure you don't want to install any additional software?"), True)
if yesno:
savePickled(software)
done = True
else:
resultList = result.split(" ")
yesno = whiptailBox("yesno", _("Are you sure?"), _("Are you sure you want to install this software?") + " \n" + (result.replace(" ", "\n")), True, height=str(7+len(result.split(" "))))
if yesno:
for i in software:
if i.name in resultList:
i.customAptPip()
#i.marked = True
done = True
savePickled(software)
if holdOffInstall == False:
installSoftwareFromFile()
开发者ID:MTRNord,项目名称:PiNet,代码行数:50,代码来源:pinet-functions-python.py
示例8: triple_column_print
def triple_column_print(iterable):
chunk_count = 3
max_width = shutil.get_terminal_size().columns
chunk_size = (max_width - 4) // chunk_count
args = [iter(iterable)] * chunk_count
for triplet in itertools.zip_longest(fillvalue='', *args):
print(' {0:<{width}}{1:^{width}}{2:>{width}} '.format(width=chunk_size, *triplet))
开发者ID:robeastham,项目名称:gtd.py,代码行数:7,代码来源:input.py
示例9: table_print
def table_print(self, title='', columns='', nextt=False):
"""Функция форматирует вывод в виде таблички"""
space = lambda s, m: (s,
" " * (m - len(s))) if len(s) <= m else (s[:m - 1], '')
listmerge = lambda s: reduce(lambda d, el: d.extend(el) or d, s, [])
maximum = shutil.get_terminal_size((80, 20))[0] - 1
def cwidth(cn):
"Функция вычисляет ширину каждого из столбцов"
free = maximum - cn - 1
tmp = int(free / cn)
width = [tmp for n in range(cn)]
if free % cn != 0:
width[0] += free % cn
return width
if not nextt:
print("-" * maximum)
if title:
print("|%s%s|" % space(title, maximum - 2))
print("-" * maximum)
if columns:
sp = cwidth(len(columns[0]))
for c in columns:
print(("|%s%s" * len(columns[0]) + "|") %
tuple(listmerge(
[space(c[i], sp[i]) for i in range(len(c))])))
print("-" * maximum)
开发者ID:kuchiman,项目名称:wpm,代码行数:29,代码来源:WinPackManager.py
示例10: __init__
def __init__(self, network):
"""This doesn't really need a docstring, does it?"""
self.network = network
self.quitting = False
self.mode = self.Mode.list
self.current_entity = None
self.status = "Started PIMesh"
self.titlebar = "PIMesh"
self.cols, self.lines = shutil.get_terminal_size()
self.used_lines = 0 # Used for vertical padding
self.commands = {
"duck": self.command_duck,
"list": self.command_list,
"view": self.command_view,
"help": self.command_help,
"add": self.command_add,
"remove": self.command_remove,
"quit": self.command_quit,
}
self.mode_content = {
UI.Mode.list: self.list_print,
UI.Mode.links: self.links_print,
UI.Mode.help: self.help_print,
UI.Mode.duck: self.duck_print
}
开发者ID:BinkyToo,项目名称:PIMesh,代码行数:30,代码来源:cliui.py
示例11: calendar
def calendar(collection, dates=None, firstweekday=0, locale=None,
weeknumber=False, show_all_days=False, conf=None,
hmethod='fg',
default_color='',
multiple='',
color='',
highlight_event_days=0,
week=False,
full=False,
bold_for_light_color=True,
**kwargs):
if dates is None:
dates = [datetime.today()]
term_width, _ = get_terminal_size()
lwidth = 25
rwidth = term_width - lwidth - 4
event_column = get_agenda(
collection, locale, dates=dates, width=rwidth,
show_all_days=show_all_days, week=week, full=full,
bold_for_light_color=bold_for_light_color, **kwargs)
calendar_column = calendar_display.vertical_month(
firstweekday=firstweekday, weeknumber=weeknumber,
collection=collection,
hmethod=hmethod,
default_color=default_color,
multiple=multiple,
color=color,
highlight_event_days=highlight_event_days,
locale=locale,
bold_for_light_color=bold_for_light_color)
rows = merge_columns(calendar_column, event_column)
echo('\n'.join(rows))
开发者ID:Ben-Baert,项目名称:khal,代码行数:33,代码来源:controllers.py
示例12: agenda
def agenda(collection, dates=None, show_all_days=False, full=False,
week=False, bold_for_light_color=True, **kwargs):
term_width, _ = get_terminal_size()
event_column = get_agenda(
collection, dates=dates, width=term_width, show_all_days=show_all_days,
full=full, week=week, bold_for_light_color=bold_for_light_color, **kwargs)
echo('\n'.join(event_column))
开发者ID:hsanson,项目名称:khal,代码行数:7,代码来源:controllers.py
示例13: test_echo_request_line
def test_echo_request_line():
sio = io.StringIO()
d = dumper.Dumper(sio)
with taddons.context(options=options.Options()) as ctx:
ctx.configure(d, flow_detail=3, showhost=True)
f = tflow.tflow(client_conn=None, server_conn=True, resp=True)
f.request.is_replay = True
d._echo_request_line(f)
assert "[replay]" in sio.getvalue()
sio.truncate(0)
f = tflow.tflow(client_conn=None, server_conn=True, resp=True)
f.request.is_replay = False
d._echo_request_line(f)
assert "[replay]" not in sio.getvalue()
sio.truncate(0)
f = tflow.tflow(client_conn=None, server_conn=True, resp=True)
f.request.http_version = "nonstandard"
d._echo_request_line(f)
assert "nonstandard" in sio.getvalue()
sio.truncate(0)
ctx.configure(d, flow_detail=0, showhost=True)
f = tflow.tflow(client_conn=None, server_conn=True, resp=True)
terminalWidth = max(shutil.get_terminal_size()[0] - 25, 50)
f.request.url = "http://address:22/" + ("x" * terminalWidth) + "textToBeTruncated"
d._echo_request_line(f)
assert "textToBeTruncated" not in sio.getvalue()
sio.truncate(0)
开发者ID:davidpshaw,项目名称:mitmproxy,代码行数:30,代码来源:test_dumper.py
示例14: _dlnotice
def _dlnotice(self):
while self.dcc is not None:
pos = self.received_bytes/self.size
pos = int(30*pos)
posstr = (("="*pos)+">").ljust(30, " ")
if self.warning:
extra = ">> " + self.warning + " <<"
if self._short_warning:
self.warning = ""
else:
extra = repr(self.original_filename)
# Make sure the status line fits the screen.
term_size = shutil.get_terminal_size((80,20))
if term_size.columns > 100:
# Calcculate speed meter.
speed = " ---.-- "
if self.received_bytes != 0:
byte_delta = self.received_bytes - self._bar_received_bytes
speed = " %8s/s"%humansize(byte_delta)
self._bar_received_bytes = self.received_bytes
else:
speed = ""
# Generate the new one.
string = "".join(("\r%8s/%8s"%(
humansize(self.received_bytes),
humansize(self.size)
), speed, " [", posstr, "] ", extra, " "))
self._write_status(string)
time.sleep(1)
开发者ID:StuxSoftware,项目名称:term-xdcc,代码行数:35,代码来源:xdcc.py
示例15: __init__
def __init__(self, message, totalCount = None, disp=True):
if not disp or sys.platform == 'win32':
self.update = self.empty
self.curlUpdate = self.empty
self.progress = self.empty
self.progressBy = self.empty
self.outputProgress = self.empty
self.done = self.empty
self.main = ''
self.finished = 0
return
# windows system does not support ncurse
import blessings
self.term = blessings.Terminal(stream=sys.stderr)
self.main = message
self.main_start_time = time.time()
self.message = self.main
# get terminal width
self.term_width = shutil.get_terminal_size((80, 20)).columns
#
# total count
self.count = 0
# total initial count
self.init_count = self.count
#
self.finished = 0
self.uuid = uuid.uuid4().hex
with fasteners.InterProcessLock('/tmp/sos_progress_'):
with open('/tmp/sos_progress', 'a') as prog_index:
prog_index.write('{}\n'.format(self.uuid))
self.reset('', totalCount)
开发者ID:BoPeng,项目名称:SOS,代码行数:31,代码来源:utils.py
示例16: __init__
def __init__(self):
self.term_width = shutil.get_terminal_size().columns
self.formater = lambda prog: argparse.HelpFormatter(prog, max_help_position=int(self.term_width / 2), width=self.term_width)
self.commands = {}
self.hidden_commands = []
self.parser = argparse.ArgumentParser(prog='meson', formatter_class=self.formater)
self.subparsers = self.parser.add_subparsers(title='Commands',
description='If no command is specified it defaults to setup command.')
self.add_command('setup', msetup.add_arguments, msetup.run,
help_msg='Configure the project')
self.add_command('configure', mconf.add_arguments, mconf.run,
help_msg='Change project options',)
self.add_command('install', minstall.add_arguments, minstall.run,
help_msg='Install the project')
self.add_command('introspect', mintro.add_arguments, mintro.run,
help_msg='Introspect project')
self.add_command('init', minit.add_arguments, minit.run,
help_msg='Create a new project')
self.add_command('test', mtest.add_arguments, mtest.run,
help_msg='Run tests')
self.add_command('wrap', wraptool.add_arguments, wraptool.run,
help_msg='Wrap tools')
self.add_command('subprojects', msubprojects.add_arguments, msubprojects.run,
help_msg='Manage subprojects')
self.add_command('help', self.add_help_arguments, self.run_help_command,
help_msg='Print help of a subcommand')
self.add_command('rewrite', lambda parser: rewriter.add_arguments(parser, self.formater), rewriter.run,
help_msg='Modify the project definition')
# Hidden commands
self.add_command('runpython', self.add_runpython_arguments, self.run_runpython_command,
help_msg=argparse.SUPPRESS)
self.add_command('unstable-coredata', munstable_coredata.add_arguments, munstable_coredata.run,
help_msg=argparse.SUPPRESS)
开发者ID:mesonbuild,项目名称:meson,代码行数:35,代码来源:mesonmain.py
示例17: printPaths
def printPaths(self, compact=False):
"""""
Prints the paths in this DotConfig, with a source and destination
for the symlink, the paths are expanded by default
"""
(cols, rows) = shutil.get_terminal_size()
print( CLS.lightblue + (cols * "-")+ CLS.none)
print(" Files for package: "+ CLS.green + self.package_name + CLS.none)
print( CLS.lightblue + (cols * "-")+ CLS.none)
paths_dict = dict()
if compact :
paths_dict = self.paths_dict
else:
paths_dict = self.expanded_paths_dict
for f in paths_dict:
source = f
dest = paths_dict[f]
print(CLS.yellow+"Symlink: " +
CLS.green + dest +
CLS.none+" >> "+
CLS.lightblue + source + CLS.none)
开发者ID:j-g-,项目名称:dotfiles,代码行数:26,代码来源:dotfiles.py
示例18: _get_terminal_size
def _get_terminal_size():
if platform.system() == "Windows":
#######################
## Copied from i-net ##
#######################
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
import struct
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
else:
sizex, sizey = 80, 25
return sizex
else:
import shutil
str = shutil.get_terminal_size()
intList = re.findall(r'\d+', "{0}".format(str))
return int(intList[0])
开发者ID:mr55p,项目名称:CS,代码行数:25,代码来源:core.py
示例19: __init__
def __init__(self, text, width, options=ProgressBarOptions()):
"""
Create ProgressBar object
:argument text Text of the ProgressBar
:argument options Format of progress Bar
:type text str
:type width int
:type options ProgressBarOptions
"""
self._text = text
self._status_msg = ""
self._width = width
self._max = 0
self._console_width = get_terminal_size(fallback=(80, 24))[0]
self._value = None
self._timer = _ProgressBarTiming()
self._begin_line_character = '\r'
self._options = options
self._infinite_mode = None
self._infinite_position = None
self._infinite_width = 1
self.stdout = sys.stdout
self._status = ProgressBarStatus.stopped
开发者ID:hapylestat,项目名称:appcore,代码行数:25,代码来源:progress_bar.py
示例20: vocabResults
def vocabResults(word):
url = 'https://www.vocabulary.com/dictionary/' + word
response = requests.get(url, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:49.0) Gecko/20100101 Firefox/49.0"})
html = response.content
vocab_soup = BeautifulSoup(html, "lxml")
[vocab_soup, suggestedWord] = handleVocabDidYouMean(vocab_soup, word)
columns = shutil.get_terminal_size().columns
print(color.getMagenta(word.upper().center(columns)))
short = vocab_soup.find("p", {"class":"short"})
if short != None:
print(color.getRed(printAligned("SHORT ", short.text)))
lonng = vocab_soup.find("p", {"class":"long"})
if lonng != None:
print(color.getDarkCyan(printAligned("LONG ", lonng.text)))
json_url = 'https://corpus.vocabulary.com/api/1.0/examples.json?query=' + str(word) + '&maxResults=24&startOffset=0&filter=0'
json_url = json_url.replace(' ', '%20')
html = urllib.request.urlopen(json_url).read()
j = json.loads(html.decode('utf-8'))
if j['result'] != None:
l = j['result']['sentences']
print("Examples from Vocabulary:".upper().center(columns))
for s in l[:5]:
print(color.getItalics(printAligned(" > ", s['sentence'])))
return word
开发者ID:chaser3,项目名称:Projects,代码行数:25,代码来源:groupMean.py
注:本文中的shutil.get_terminal_size函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论