本文整理汇总了Python中blessed.Terminal.move方法的典型用法代码示例。如果您正苦于以下问题:Python Terminal.move方法的具体用法?Python Terminal.move怎么用?Python Terminal.move使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类blessed.Terminal
的用法示例。
在下文中一共展示了Terminal.move方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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()
示例2: participant_context
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
def participant_context(exp: Experiment, participant: ExperimentSection):
term = Terminal()
exp.session_data['term'] = term
exp.session_data['stimuli'] = [
jpg_to_ascii(os.path.join('stimuli', '{:02}.jpg'.format(i)), background='light', height=term.height - 2)
for i in range(1, 16)
]
with term.fullscreen():
print(term.move(int(term.width//2), int(term.height//2)))
response_type = participant.data['response_type']
instructions = exp.experiment_data['instructions']
for i, instruction in enumerate(instructions, 1):
message = get_message(instruction, response_type)
if message.startswith('_example'):
show_example(term, response_type, message.split('_')[2], exp.session_data['stimuli'],
exp.experiment_data['example_response_message'],
ascii_stimuli=exp.experiment_data.get('ascii_stimuli', True),
stimulus_time=8)
else:
reset(term)
wrapped_multiline_print_at_location(term, message, X_MARGIN, Y_MARGIN, int(term.width//2))
with term.location(term.width//2, term.height - 3):
print('{}/{}'.format(i, len(instructions)))
time.sleep(1) # Ensure we don't accidentally skip a message.
input()
yield
reset(term)
print(exp.experiment_data['exit_message'])
input()
del exp.session_data['term']
示例3: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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()
示例4: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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.
"""
term = Terminal()
score = level = hit_highbit = hit_unicode = 0
dirty = True
def refresh(term, board, level, score, inp):
sys.stdout.write(term.home + term.clear)
level_color = level % 7
if level_color == 0:
level_color = 4
bottom = 0
for keycode, attr in board.items():
sys.stdout.write(u''.join((
term.move(attr['row'], attr['column']),
term.color(level_color),
(term.reverse if attr['hit'] else term.bold),
keycode,
term.normal)))
bottom = max(bottom, attr['row'])
sys.stdout.write(term.move(term.height, 0)
+ 'level: %s score: %s' % (level, score,))
sys.stdout.flush()
if bottom >= (term.height - 5):
sys.stderr.write(
'\n' * (term.height / 2) +
term.center(term.red_underline('cheater!')) + '\n')
sys.stderr.write(
term.center("(use a larger screen)") +
'\n' * (term.height / 2))
sys.exit(1)
for row, inp in enumerate(inps[(term.height - (bottom + 2)) * -1:]):
sys.stdout.write(term.move(bottom + row+1))
sys.stdout.write('%r, %s, %s' % (inp.__str__() if inp.is_sequence
else inp, inp.code, inp.name, ))
sys.stdout.flush()
def build_gameboard(term):
column, row = 0, 0
board = dict()
spacing = 2
for keycode in sorted(term._keycodes.values()):
if (keycode.startswith('KEY_F')
and keycode[-1].isdigit()
and int(keycode[len('KEY_F'):]) > 24):
continue
if column + len(keycode) + (spacing * 2) >= term.width:
column = 0
row += 1
board[keycode] = {'column': column,
'row': row,
'hit': 0,
}
column += len(keycode) + (spacing * 2)
return board
def add_score(score, pts, level):
lvl_multiplier = 10
score += pts
if 0 == (score % (pts * lvl_multiplier)):
level += 1
return score, level
gb = build_gameboard(term)
inps = []
with term.raw():
inp = term.inkey(timeout=0)
while inp.upper() != 'Q':
if dirty:
refresh(term, gb, level, score, inps)
dirty = False
inp = term.inkey(timeout=5.0)
dirty = True
if (inp.is_sequence and
inp.name in gb and
0 == gb[inp.name]['hit']):
gb[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():
sys.stdout.write(u''.join((
term.move(term.height),
term.clear_eol,
u'Your final score was %s' % (score,),
u' at level %s' % (level,),
term.clear_eol,
u'\n',
#.........这里部分代码省略.........
示例5: monitor
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
def monitor(run_once=False):
term = Terminal()
r = redis_client
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('Status', 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:
# color status
if stat.status == Conf.WORKING:
status = term.green(Conf.WORKING)
elif stat.status == Conf.STOPPED:
status = term.red(Conf.STOPPED)
elif stat.status == Conf.IDLE:
status = Conf.IDLE
else:
status = term.yellow(stat.status)
# 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)
示例6: BrowseRouters
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
class BrowseRouters(message.MessageSending):
log = logging.getLogger(__name__)
SCHEMA = '''CREATE TABLE routers (
id TEXT PRIMARY KEY,
name TEXT,
status TEXT,
latest INTEGER,
image_name TEXT,
last_fetch TIMESTAMP,
booted_at TIMESTAMP
);'''
def __init__(self, *a, **kw):
self.term = Terminal()
self.position = 0
self.routers = []
super(BrowseRouters, self).__init__(*a, **kw)
def init_database(self):
self.fh = tempfile.NamedTemporaryFile(delete=False)
self.conn = sqlite3.connect(self.fh.name)
self.conn.row_factory = RouterRow.from_cursor
with closing(self.conn.cursor()) as cursor:
cursor.execute(self.SCHEMA)
def get_parser(self, prog_name):
parser = super(BrowseRouters, self).get_parser(prog_name)
parser.add_argument('--dump', dest='interactive', action='store_false')
parser.add_argument('--threads', type=int, default=16)
parser.set_defaults(interactive=True)
return parser
def take_action(self, parsed_args):
self.interactive = parsed_args.interactive
self.init_database()
credentials = [
cfg.CONF.admin_user,
cfg.CONF.admin_password,
cfg.CONF.admin_tenant_name,
cfg.CONF.auth_url,
cfg.CONF.auth_strategy,
cfg.CONF.auth_region
]
populate = threading.Thread(
name='router-populater',
target=populate_routers,
args=(self.fh.name, credentials, parsed_args.threads)
)
populate.setDaemon(True)
populate.start()
self.handle_loop()
def handle_loop(self):
try:
with self.term.fullscreen():
with self.term.cbreak():
val = None
while val != u'q':
if not val:
self.fetch_routers()
elif val.is_sequence:
if val.code == self.term.KEY_DOWN:
self.move_down()
if val.code == self.term.KEY_UP:
self.move_up()
elif val == u'j':
self.move_down()
elif val == u'k':
self.move_up()
elif val == u'r':
self.rebuild_router()
if self.interactive:
self.print_routers()
val = self.term.inkey(timeout=3)
elif len(self.routers) and all(map(
lambda x: x.last_fetch, self.routers
)):
self.print_routers()
val = u'q'
self._exit()
except KeyboardInterrupt:
self._exit()
raise
def fetch_routers(self):
with self.conn:
cursor = self.conn.cursor()
cursor.execute('SELECT * FROM routers ORDER BY id ASC;')
self.routers = cursor.fetchall()
@property
def window(self):
offset = 0
routers = self.routers
visible_height = self.term.height - 2
if len(routers) > visible_height:
offset = self.position
offset = min(offset, len(routers) - visible_height - 1)
return offset, routers[offset:(offset+visible_height+1)]
#.........这里部分代码省略.........
示例7: main
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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')))
示例8: monitor
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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)
示例9: monitor
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [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)
示例10: reset
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
def reset(term: Terminal):
print(term.clear())
print(term.move(0, 0))
示例11: RokuCLI
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
class RokuCLI():
""" Command-line interpreter for processing user input and relaying
commands to Roku """
def __init__(self):
self.term = Terminal()
self.roku = None
def parseargs(self):
parser = argparse.ArgumentParser(
description='Interactive command-line control of Roku devices')
parser.add_argument(
'ipaddr',
nargs='?',
help=('IP address of Roku to connect to. By default, will ' +
'automatically detect Roku within LAN.'))
return parser.parse_args()
def text_entry(self):
""" Relay literal text entry from user to Roku until
<Enter> or <Esc> pressed. """
allowed_sequences = set(['KEY_ENTER', 'KEY_ESCAPE', 'KEY_DELETE'])
sys.stdout.write('Enter text (<Esc> to abort) : ')
sys.stdout.flush()
# Track start column to ensure user doesn't backspace too far
start_column = self.term.get_location()[1]
cur_column = start_column
with self.term.cbreak():
val = ''
while val != 'KEY_ENTER' and val != 'KEY_ESCAPE':
val = self.term.inkey()
if not val:
continue
elif val.is_sequence:
val = val.name
if val not in allowed_sequences:
continue
if val == 'KEY_ENTER':
self.roku.enter()
elif val == 'KEY_ESCAPE':
pass
elif val == 'KEY_DELETE':
self.roku.backspace()
if cur_column > start_column:
sys.stdout.write(u'\b \b')
cur_column -= 1
else:
self.roku.literal(val)
sys.stdout.write(val)
cur_column += 1
sys.stdout.flush()
# Clear to beginning of line
sys.stdout.write(self.term.clear_bol)
sys.stdout.write(self.term.move(self.term.height, 0))
sys.stdout.flush()
def run(self):
ipaddr = self.parseargs().ipaddr
# If IP not specified, use Roku discovery and let user choose
if ipaddr:
self.roku = Roku(ipaddr)
else:
self.roku = discover_roku()
if not self.roku:
return
print(usage_menu)
cmd_func_map = {
'B': self.roku.back,
'KEY_DELETE': self.roku.back,
'H': self.roku.home,
'h': self.roku.left,
'KEY_LEFT': self.roku.left,
'j': self.roku.down,
'KEY_DOWN': self.roku.down,
'k': self.roku.up,
'KEY_UP': self.roku.up,
'l': self.roku.right,
'KEY_RIGHT': self.roku.right,
'KEY_ENTER': self.roku.select,
'R': self.roku.replay,
'i': self.roku.info,
'r': self.roku.reverse,
'f': self.roku.forward,
' ': self.roku.play,
'/': self.text_entry}
# Main interactive loop
with self.term.cbreak():
val = ''
while val.lower() != 'q':
val = self.term.inkey()
#.........这里部分代码省略.........
示例12: tprint
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
import sys
from blessed import Terminal
from multiprocessing import Pool, cpu_count
import numpy as np
origin_x, origin_y = 1, 1
def tprint(ustr):
y = t.get_location()[0]
x = t.get_location()[1]
print(t.move(origin_y + y, origin_x + x) + str(ustr))
t = Terminal()
t.move(origin_y, origin_x)
with t.fullscreen():
def worker(arr):
return arr * 2 + 1
tprint("Start processing data...")
data_arr = np.random.rand(8, int(1e7))
with Pool(cpu_count()) as p:
buffer = p.map(worker, [data_arr[row] for row in np.ndindex(data_arr.shape[0])])
tprint("...finished processing:")
for row in buffer:
tprint(row[0:3])
示例13: range
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
return line
for i in range(layers_length):
offset = 1 if i < last else 0
for j in range(term.height - offset):
layers[i].append(generate_line(i + 1))
for i in range(prog_len - 1):
progress[progress_template[i]] = progress_template[i + 1]
progress[progress_template[prog_len - 1]] = progress_template[prog_len - 1]
with term.fullscreen(), term.hidden_cursor():
while not term.inkey(timeout=0.15):
out = term.move(0, 0)
for i in range(term.height - 1):
for j in range(term.width):
any = False
for k in reversed(range(len(layers))):
if layers[k][i][j]:
any = True
out += snow[k]
break
if not any:
out += u' '
out += u'\n'
示例14: CalculonDisplay
# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import move [as 别名]
#.........这里部分代码省略.........
def num_rows(self):
return self.offset_exprs() + self.num_rows_exprs() + self.padding['bottom']
def num_cols(self):
if self.cur_bin_mode == "wide":
c = BIN_MODE_WIDTH_WIDE + self.padding['left'] + self.padding['right']
else:
c = BIN_MODE_WIDTH_NARROW + self.padding['left'] + self.padding['right']
return c
def num_rows_val(self):
return len(self.get_value_formats())
def num_rows_bin(self):
return int(self.bits / self.bin_row + self.padding['bintop'] + self.padding['binbottom'])
def num_rows_exprs(self):
n = len(self.exprs)
if n > 0:
n += self.padding['vartop'] + self.padding['varbottom']
return n
def offset_val(self):
return self.padding['top']
def offset_bin(self):
return self.offset_val() + self.num_rows_val()
def offset_exprs(self):
return self.offset_bin() + self.num_rows_bin()
def draw_str(self, str, attr='', x=0, y=0):
print((self.term.normal + self.term.move(y, x) + attr + str).format(t=self.term))
def draw_header(self):
if self.show_header:
self.draw_str(' ' * self.term.width, self.attrs['header'], 0, 0)
self.draw_str(self.header, self.attrs['header'], self.padding['left'] )
def clear_value(self, varname=None):
y = self.padding['top']
for fmt in self.get_value_formats():
w = self.num_cols() - self.padding['left'] - len(' ' + fmt) - self.padding['right'] - self.padding['label']*2
x = self.padding['left'] + len(' ' + fmt)
if varname:
w -= len(varname)
if self.align == 'right':
x += len(varname)
self.draw_str(' '*w, '', x, y)
y += 1
def draw_value(self, varname=None):
y = self.padding['top']
for fmt in self.get_value_formats():
self.draw_value_at_row(self.lastval, fmt, y)
y += 1
def draw_value_at_row(self, value, fmt, row, label=None):
if value == None:
fmtd = '<undefined>'
attr = self.attrs['err']
else:
fmtd = ''
if fmt in ['h', 'd', 'o']:
fmtd = BASE_FMT[fmt].format(value)