本文整理汇总了Python中blessed.Terminal.inkey方法的典型用法代码示例。如果您正苦于以下问题:Python Terminal.inkey方法的具体用法?Python Terminal.inkey怎么用?Python Terminal.inkey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类blessed.Terminal
的用法示例。
在下文中一共展示了Terminal.inkey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
"""Program entry point."""
term = Terminal()
score = level = hit_highbit = hit_unicode = 0
dirty = True
gameboard = build_gameboard(term)
inps = []
with term.raw(), term.keypad(), term.location():
inp = term.inkey(timeout=0)
while inp != chr(3):
if dirty:
refresh(term, gameboard, level, score, inps)
dirty = False
inp = term.inkey(timeout=5.0)
dirty = True
if (inp.is_sequence and
inp.name in gameboard and
0 == gameboard[inp.name]['hit']):
gameboard[inp.name]['hit'] = 1
score, level = add_score(score, 100, level)
elif inp and not inp.is_sequence and 128 <= ord(inp) <= 255:
hit_highbit += 1
if hit_highbit < 5:
score, level = add_score(score, 100, level)
elif inp and not inp.is_sequence and ord(inp) > 256:
hit_unicode += 1
if hit_unicode < 5:
score, level = add_score(score, 100, level)
inps.append(inp)
with term.cbreak():
echo(term.move(term.height))
echo(
u'{term.clear_eol}Your final score was {score} '
u'at level {level}{term.clear_eol}\n'
u'{term.clear_eol}\n'
u'{term.clear_eol}You hit {hit_highbit} '
u' 8-bit characters\n{term.clear_eol}\n'
u'{term.clear_eol}You hit {hit_unicode} '
u' unicode characters.\n{term.clear_eol}\n'
u'{term.clear_eol}press any key\n'.format(
term=term,
score=score, level=level,
hit_highbit=hit_highbit,
hit_unicode=hit_unicode)
)
term.inkey()
示例2: inputter
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def inputter():
term = Terminal()
with term.cbreak():
key = term.inkey(1)
if key and not key.is_sequence:
return key
return None
示例3: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
"""
Displays all known key capabilities that may match the terminal.
As each key is pressed on input, it is lit up and points are scored.
"""
try:
from x84.bbs import getterminal, echo
term = getterminal()
except (ImportError, AttributeError):
from blessed import Terminal
import sys
term = Terminal()
def echo(text):
sys.stdout.write(u"{}".format(text))
sys.stdout.flush()
echo(u"".join((term.normal, term.height * u"\r\n", term.home, term.clear_eos)))
with term.raw():
inp = u""
echo(u"Press Q to exit.\r\n")
while inp.upper() != "Q":
inp = term.inkey(timeout=10.0)
disp_inp = inp.__str__() if inp.is_sequence else inp
echo(u"{0!r}: code={1!r} name={2!r}\r\n".format(disp_inp, inp.code, inp.name))
示例4: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
"""Program entry point."""
term = Terminal()
assert term.hpa(1) != u'', (
'Terminal does not support hpa (Horizontal position absolute)')
col, offset = 1, 1
with term.cbreak():
inp = None
print("press 'X' to stop.")
sys.stderr.write(term.move(term.height, 0) + u'[')
sys.stderr.write(term.move_x(term.width) + u']' + term.move_x(1))
while inp != 'X':
if col >= (term.width - 2):
offset = -1
elif col <= 1:
offset = 1
sys.stderr.write(term.move_x(col))
if offset == -1:
sys.stderr.write(u'.')
else:
sys.stderr.write(u'=')
col += offset
sys.stderr.write(term.move_x(col))
sys.stderr.write(u'|\b')
sys.stderr.flush()
inp = term.inkey(0.04)
print()
示例5: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main(logfilepath):
term = Terminal()
mngr = Manager(term, num_divisions=1, logfilepath=logfilepath)
cursor, scrn = mngr.get_focus_cursor_and_screen()
with term.hidden_cursor(), \
term.raw(), \
term.location(), \
term.fullscreen(), \
term.keypad():
inp = None
while True:
inp = term.inkey(timeout=0.2)
if inp != u'':
signal = mngr.handle_input(inp)
if signal == -1:
# got exit signal
break
mngr.draw()
if mngr.logger != None:
mngr.logger.write_to_file()
示例6: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
"""Program entry point."""
term = Terminal()
def on_resize(*args):
# pylint: disable=unused-argument
# Unused argument 'args'
# Its generally not a good idea to put blocking functions (such as
# print) within a signal handler -- if another SIGWINCH is received
# while this function blocks, an error will occur.
# In most programs, you'll want to set some kind of 'dirty' flag,
# perhaps by a Semaphore like threading.Event or (thanks to the GIL)
# a simple global variable will suffice.
print('height={t.height}, width={t.width}\r'.format(t=term))
signal.signal(signal.SIGWINCH, on_resize)
# display initial size
on_resize(term)
with term.cbreak():
print("press 'X' to stop.")
inp = None
while inp != 'X':
inp = term.inkey()
print(repr(inp))
示例7: inkey
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def inkey(self, timeout=None, esc_delay=0.35):
try:
return BlessedTerminal.inkey(self, timeout, esc_delay=0.35)
except UnicodeDecodeError as err:
log = logging.getLogger(__name__)
log.warn('UnicodeDecodeError: {0}'.format(err))
return u'?'
示例8: inkey
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def inkey(self, timeout=None, esc_delay=0.35, *_):
# pylint: disable=C0111
# Missing docstring
try:
return BlessedTerminal.inkey(self, timeout, esc_delay=0.35)
except UnicodeDecodeError as err:
log = logging.getLogger(__name__)
log.warn('UnicodeDecodeError: {0}'.format(err))
return u'?'
示例9: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
term = Terminal()
csr = Cursor(0, 0, term)
screen = {}
with term.hidden_cursor(), \
term.raw(), \
term.location(), \
term.fullscreen(), \
term.keypad():
inp = None
while True:
echo_yx(csr, term.reverse(screen.get((csr.y, csr.x), u' ')))
inp = term.inkey()
if inp == chr(3):
# ^c exits
break
elif inp == chr(19):
# ^s saves
echo_yx(home(bottom(csr)),
term.ljust(term.bold_white('Filename: ')))
echo_yx(right_of(home(bottom(csr)), len('Filename: ')), u'')
save(screen, readline(term))
echo_yx(home(bottom(csr)), term.clear_eol)
redraw(term=term, screen=screen,
start=home(bottom(csr)),
end=end(bottom(csr)))
continue
elif inp == chr(12):
# ^l refreshes
redraw(term=term, screen=screen)
n_csr = lookup_move(inp.code, csr, term)
if n_csr != csr:
# erase old cursor,
echo_yx(csr, screen.get((csr.y, csr.x), u' '))
csr = n_csr
elif not inp.is_sequence and inp.isprintable():
echo_yx(csr, inp)
screen[(csr.y, csr.x)] = inp.__str__()
n_csr = right_of(csr, 1)
if n_csr == csr:
# wrap around margin
n_csr = home(below(csr, 1))
csr = n_csr
示例10: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
term = Terminal()
term.stream.write('YO >')
term.stream.flush()
termHistory = history.CommandHistory()
buffer = ''
while True:
try:
with term.cbreak():
char = term.inkey()
if char.is_sequence:
if char.name == 'KEY_UP':
termHistory.increment_index()
buffer = termHistory.get_item()
term.stream.write(term.clear_bol)
term.stream.write(term.move_x(0))
term.stream.write('YO >')
term.stream.write(buffer)
elif char.name == 'KEY_DOWN':
termHistory.decrement_index()
buffer = termHistory.get_item()
term.stream.write(term.clear_bol)
term.stream.write(term.move_x(0))
term.stream.write(term.clear_bol + 'YO >')
term.stream.write(buffer)
elif char.name == 'KEY_DELETE':
buffer = buffer[ :-1 ]
term.stream.write(term.move_left)
term.stream.write(' ')
term.stream.write(term.move_left)
elif char.name == 'KEY_ENTER':
termHistory.add(buffer)
args = buffer.split(' ')
commands = separate_by_pipe(args)
term.stream.write('\n')
run_all_commands(commands, 1)
buffer = ''
term.stream.write('YO >')
finally:
if not char.is_sequence:
buffer += char
term.stream.write(char)
term.stream.flush()
示例11: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def main():
"""Program entry point."""
# pylint: disable=too-many-locals
# Too many local variables (20/15)
term = Terminal()
worm = [Location(x=term.width // 2, y=term.height // 2)]
worm_length = 2
bearing = Direction(*LEFT)
direction = left_of
nibble = Nibble(location=worm[0], value=0)
color_nibble = term.black_on_green
color_worm = term.yellow_reverse
color_head = term.red_reverse
color_bg = term.on_blue
echo(term.move(1, 1))
echo(color_bg(term.clear))
# speed is actually a measure of time; the shorter, the faster.
speed = 0.1
modifier = 0.93
inp = None
echo(term.move(term.height, 0))
with term.hidden_cursor(), term.cbreak(), term.location():
while inp not in (u'q', u'Q'):
# delete the tail of the worm at worm_length
if len(worm) > worm_length:
echo(term.move(*worm.pop(0)))
echo(color_bg(u' '))
# compute head location
head = worm.pop()
# check for hit against self; hitting a wall results in the (y, x)
# location being clipped, -- and death by hitting self (not wall).
if hit_any(head, worm):
break
# get the next nibble, which may be equal to ours unless this
# nibble has been struck by any portion of our worm body.
n_nibble = next_nibble(term, nibble, head, worm)
# get the next worm_length and speed, unless unchanged.
worm_length = next_wormlength(nibble, head, worm_length)
speed = next_speed(nibble, head, speed, modifier)
if n_nibble != nibble:
# erase the old one, careful to redraw the nibble contents
# with a worm color for those portions that overlay.
for (yloc, xloc) in nibble_locations(*nibble):
echo(u''.join((
term.move(yloc, xloc),
(color_worm if (yloc, xloc) == head
else color_bg)(u' '),
term.normal)))
# and draw the new,
echo(term.move(*n_nibble.location) + (
color_nibble('{}'.format(n_nibble.value))))
# display new worm head
echo(term.move(*head) + color_head(head_glyph(direction)))
# and its old head (now, a body piece)
if worm:
echo(term.move(*(worm[-1])))
echo(color_worm(u' '))
echo(term.move(*head))
# wait for keyboard input, which may indicate
# a new direction (up/down/left/right)
inp = term.inkey(timeout=speed)
# discover new direction, given keyboard input and/or bearing.
nxt_direction = next_bearing(term, inp.code, bearing)
# discover new bearing, given new direction compared to prev
nxt_bearing = change_bearing(nxt_direction, head, term)
# disallow new bearing/direction when flipped: running into
# oneself, for example traveling left while traveling right.
if not bearing_flipped(bearing, nxt_bearing):
direction = nxt_direction
bearing = nxt_bearing
# append the prior `head' onto the worm, then
# a new `head' for the given direction.
worm.extend([head, direction(head, term)])
# re-assign new nibble,
nibble = n_nibble
echo(term.normal)
score = (worm_length - 1) * 100
echo(u''.join((term.move(term.height - 1, 1), term.normal)))
echo(u''.join((u'\r\n', u'score: {}'.format(score), u'\r\n')))
示例12: Console
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
class Console(threading.Thread):
def __init__(self, config, ledBulbs, animationManager):
threading.Thread.__init__(self)
self.config = config
self.ledBulbs = ledBulbs
self.animations = animationManager
self.t = Terminal()
self.topLine = 0
self.moveMode = False
self.markedLine = 2
def on_resize(*args):
self.update()
signal.signal(signal.SIGWINCH, on_resize)
self.updateThread()
def resetScreen(self):
self.topLine = 2
def renderScreen(self):
self.resetScreen()
with self.t.fullscreen():
for bulb in self.ledBulbs.orderedBulbs():
self.printTop(str(bulb), bulb.marked != 0)
self.printKeymap()
self.printStatus()
def update(self):
self.renderScreen()
@threaded
def updateThread(self):
while True:
self.update()
time.sleep(0.5)
def updateTerminal(self):
with self.t.cbreak():
val = self.t.inkey()
if val.name == "KEY_UP":
self.keyUp()
elif val.name == "KEY_DOWN":
self.keyDown()
elif val.name == "KEY_RIGHT":
self.animationNext()
elif val.name == "KEY_LEFT":
self.animationPrev()
elif val.name == "KEY_ESCAPE":
self.esc()
elif val in (" "):
self.toggleMoveMode()
else:
pass
def esc(self):
self.toggleMoveMode(0)
self.renderScreen()
def keyUp(self):
if self.moveMode == 0:
self.brightnessUp()
else:
self.markUp()
def keyDown(self):
if self.moveMode == 0:
self.brightnessDown()
else:
self.markDown()
def run(self):
self.update()
while True:
self.updateTerminal()
def markUp(self):
bulbs = self.ledBulbs.orderedBulbs()
bulb1 = bulbs[self.markedLine - 2]
if bulb1.marked == 2:
bulb2 = None
for bulb in bulbs:
if bulb.marked == 1:
bulb2 = bulb
for bulb in bulbs:
bulb.marked = 0
if bulb2 != None:
bulb2.marked = 1
else:
bulb1.marked = 1
else:
for bulb in bulbs:
bulb.marked = 0
self.markedLine -= 1
if self.markedLine < 2:
self.markedLine = 2
bulbs[self.markedLine - 2].marked = self.moveMode
#.........这里部分代码省略.........
示例13: monitor
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def monitor(run_once=False, broker=None):
if not broker:
broker = get_broker()
term = Terminal()
broker.ping()
with term.fullscreen(), term.hidden_cursor(), term.cbreak():
val = None
start_width = int(term.width / 8)
while val not in (u'q', u'Q',):
col_width = int(term.width / 8)
# In case of resize
if col_width != start_width:
print(term.clear())
start_width = col_width
print(term.move(0, 0) + term.black_on_green(term.center(_('Host'), width=col_width - 1)))
print(term.move(0, 1 * col_width) + term.black_on_green(term.center(_('Id'), width=col_width - 1)))
print(term.move(0, 2 * col_width) + term.black_on_green(term.center(_('State'), width=col_width - 1)))
print(term.move(0, 3 * col_width) + term.black_on_green(term.center(_('Pool'), width=col_width - 1)))
print(term.move(0, 4 * col_width) + term.black_on_green(term.center(_('TQ'), width=col_width - 1)))
print(term.move(0, 5 * col_width) + term.black_on_green(term.center(_('RQ'), width=col_width - 1)))
print(term.move(0, 6 * col_width) + term.black_on_green(term.center(_('RC'), width=col_width - 1)))
print(term.move(0, 7 * col_width) + term.black_on_green(term.center(_('Up'), width=col_width - 1)))
i = 2
stats = Stat.get_all(broker=broker)
print(term.clear_eos())
for stat in stats:
status = stat.status
# color status
if stat.status == Conf.WORKING:
status = term.green(str(Conf.WORKING))
elif stat.status == Conf.STOPPING:
status = term.yellow(str(Conf.STOPPING))
elif stat.status == Conf.STOPPED:
status = term.red(str(Conf.STOPPED))
elif stat.status == Conf.IDLE:
status = str(Conf.IDLE)
# color q's
tasks = str(stat.task_q_size)
if stat.task_q_size > 0:
tasks = term.cyan(str(stat.task_q_size))
if Conf.QUEUE_LIMIT and stat.task_q_size == Conf.QUEUE_LIMIT:
tasks = term.green(str(stat.task_q_size))
results = stat.done_q_size
if results > 0:
results = term.cyan(str(results))
# color workers
workers = len(stat.workers)
if workers < Conf.WORKERS:
workers = term.yellow(str(workers))
# format uptime
uptime = (timezone.now() - stat.tob).total_seconds()
hours, remainder = divmod(uptime, 3600)
minutes, seconds = divmod(remainder, 60)
uptime = '%d:%02d:%02d' % (hours, minutes, seconds)
# print to the terminal
print(term.move(i, 0) + term.center(stat.host[:col_width - 1], width=col_width - 1))
print(term.move(i, 1 * col_width) + term.center(stat.cluster_id, width=col_width - 1))
print(term.move(i, 2 * col_width) + term.center(status, width=col_width - 1))
print(term.move(i, 3 * col_width) + term.center(workers, width=col_width - 1))
print(term.move(i, 4 * col_width) + term.center(tasks, width=col_width - 1))
print(term.move(i, 5 * col_width) + term.center(results, width=col_width - 1))
print(term.move(i, 6 * col_width) + term.center(stat.reincarnations, width=col_width - 1))
print(term.move(i, 7 * col_width) + term.center(uptime, width=col_width - 1))
i += 1
# bottom bar
i += 1
queue_size = broker.queue_size()
lock_size = broker.lock_size()
if lock_size:
queue_size = '{}({})'.format(queue_size, lock_size)
print(term.move(i, 0) + term.white_on_cyan(term.center(broker.info(), width=col_width * 2)))
print(term.move(i, 2 * col_width) + term.black_on_cyan(term.center(_('Queued'), width=col_width)))
print(term.move(i, 3 * col_width) + term.white_on_cyan(term.center(queue_size, width=col_width)))
print(term.move(i, 4 * col_width) + term.black_on_cyan(term.center(_('Success'), width=col_width)))
print(term.move(i, 5 * col_width) + term.white_on_cyan(
term.center(models.Success.objects.count(), width=col_width)))
print(term.move(i, 6 * col_width) + term.black_on_cyan(term.center(_('Failures'), width=col_width)))
print(term.move(i, 7 * col_width) + term.white_on_cyan(
term.center(models.Failure.objects.count(), width=col_width)))
# for testing
if run_once:
return Stat.get_all(broker=broker)
print(term.move(i + 2, 0) + term.center(_('[Press q to quit]')))
val = term.inkey(timeout=1)
示例14: monitor
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def monitor(run_once=False):
term = Terminal()
r = redis_client
try:
redis_client.ping()
except Exception as e:
print(term.red("Can not connect to Redis server."))
logger.exception(e)
raise e
with term.fullscreen(), term.hidden_cursor(), term.cbreak():
val = None
start_width = int(term.width / 8)
while val not in (u"q", u"Q"):
col_width = int(term.width / 8)
# In case of resize
if col_width != start_width:
print(term.clear)
start_width = col_width
print(term.move(0, 0) + term.black_on_green(term.center(_("Host"), width=col_width - 1)))
print(term.move(0, 1 * col_width) + term.black_on_green(term.center(_("Id"), width=col_width - 1)))
print(term.move(0, 2 * col_width) + term.black_on_green(term.center(_("State"), width=col_width - 1)))
print(term.move(0, 3 * col_width) + term.black_on_green(term.center(_("Pool"), width=col_width - 1)))
print(term.move(0, 4 * col_width) + term.black_on_green(term.center(_("TQ"), width=col_width - 1)))
print(term.move(0, 5 * col_width) + term.black_on_green(term.center(_("RQ"), width=col_width - 1)))
print(term.move(0, 6 * col_width) + term.black_on_green(term.center(_("RC"), width=col_width - 1)))
print(term.move(0, 7 * col_width) + term.black_on_green(term.center(_("Up"), width=col_width - 1)))
i = 2
stats = Stat.get_all(r=r)
print(term.clear_eos())
for stat in stats:
status = stat.status
# color status
if stat.status == Conf.WORKING:
status = term.green(str(Conf.WORKING))
elif stat.status == Conf.STOPPING:
status = term.yellow(str(Conf.STOPPING))
elif stat.status == Conf.STOPPED:
status = term.red(str(Conf.STOPPED))
elif stat.status == Conf.IDLE:
status = str(Conf.IDLE)
# color q's
tasks = stat.task_q_size
if tasks > 0:
tasks = term.cyan(str(tasks))
results = stat.done_q_size
if results > 0:
results = term.cyan(str(results))
# color workers
workers = len(stat.workers)
if workers < Conf.WORKERS:
workers = term.yellow(str(workers))
# format uptime
uptime = (timezone.now() - stat.tob).total_seconds()
hours, remainder = divmod(uptime, 3600)
minutes, seconds = divmod(remainder, 60)
uptime = "%d:%02d:%02d" % (hours, minutes, seconds)
# print to the terminal
print(term.move(i, 0) + term.center(stat.host[: col_width - 1], width=col_width - 1))
print(term.move(i, 1 * col_width) + term.center(stat.cluster_id, width=col_width - 1))
print(term.move(i, 2 * col_width) + term.center(status, width=col_width - 1))
print(term.move(i, 3 * col_width) + term.center(workers, width=col_width - 1))
print(term.move(i, 4 * col_width) + term.center(tasks, width=col_width - 1))
print(term.move(i, 5 * col_width) + term.center(results, width=col_width - 1))
print(term.move(i, 6 * col_width) + term.center(stat.reincarnations, width=col_width - 1))
print(term.move(i, 7 * col_width) + term.center(uptime, width=col_width - 1))
i += 1
# for testing
if run_once:
return Stat.get_all(r=r)
print(term.move(i + 2, 0) + term.center(_("[Press q to quit]")))
val = term.inkey(timeout=1)
示例15: handle_keyboard
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import inkey [as 别名]
def handle_keyboard(future):
term = Terminal()
with term.cbreak():
keypress = term.inkey()
#print('got: {}'.format(keypress))
future.set_result(keypress)