当前位置: 首页>>代码示例>>Python>>正文


Python Terminal.cbreak方法代码示例

本文整理汇总了Python中blessed.Terminal.cbreak方法的典型用法代码示例。如果您正苦于以下问题:Python Terminal.cbreak方法的具体用法?Python Terminal.cbreak怎么用?Python Terminal.cbreak使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在blessed.Terminal的用法示例。


在下文中一共展示了Terminal.cbreak方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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))
开发者ID:cjfuller,项目名称:blessed,代码行数:30,代码来源:on_resize.py

示例2: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def main(argv=sys.argv[1:]):
	args = ArgumentParser()
	args.add_argument("-s", "--servers", default=DEFAULT_ES_SERVER,
		help='A list of elastic search servers seperated by "," against which to run queries (Default: %(default)s)')
	
	options = args.parse_args(argv)
	
	# post process argparsing results
	options.servers = [x.strip() for x in options.servers.split(",")]
	
	loop = asyncio.get_event_loop()
	t = Terminal()
	
	# Do this as a fullscreen app where possible to avoid poluting
	# terminal and screwing up cursor position
	with t.fullscreen():
		with t.cbreak():
			# this blank print statment forces blessings to go to 
			# 'all screen' mode as it wont send output out stdout
			# on its own
			print(t.clear)
			render_query_field(t, "")
			render_search_results(t, [])
	
			sys.stdout.flush()
	
			try:
				loop.run_until_complete(display_loop(t, options.servers))
			except KeyboardInterrupt:
				# We want to catch this as its out primary exit method. if
				# uncaught we end up displaying a interleaved (with old output)
				# stack trace that would incorectly lead users to assume they 
				# crashed the program
				print("Exiting")
开发者ID:exec-all,项目名称:numad,代码行数:36,代码来源:cmd.py

示例3: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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()
开发者ID:jquast,项目名称:blessed,代码行数:30,代码来源:progress_bar.py

示例4: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def main():
    """Program entry point."""
    term = Terminal()

    # move to bottom of screen, temporarily, where we're likely to do
    # the least damage, as we are performing something of a "destructive
    # write and erase" onto this screen location.
    with term.cbreak(), term.location(y=term.height - 1, x=0):

        # store first position
        pos0 = get_pos(term)

        # display multibyte character
        print(u'⦰', end='')

        # store second position
        pos1 = get_pos(term)

        # determine distance
        horizontal_distance = pos1.column - pos0.column
        multibyte_capable = bool(horizontal_distance == 1)

        # rubout character(s)
        print('\b \b' * horizontal_distance, end='')

    # returned to our original starting position,
    if not multibyte_capable:
        print('multibyte encoding failed, horizontal distance is {0}, '
              'expected 1 for unicode point https://codepoints.net/U+29B0'
              .format(horizontal_distance), file=sys.stderr)
        exit(1)

    print('{checkbox} multibyte encoding supported!'
          .format(checkbox=term.bold_green(u'✓')))
开发者ID:cjfuller,项目名称:blessed,代码行数:36,代码来源:detect-multibyte.py

示例5: inputter

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def inputter():
    term = Terminal()
    with term.cbreak():
        key = term.inkey(1)
        if key and not key.is_sequence:
            return key
        return None
开发者ID:grobolom,项目名称:TwitterCLI,代码行数:9,代码来源:main.py

示例6: ascii_credits

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def ascii_credits():
    """
    Asciimatics credits!
    """
    term = Terminal()
    with term.fullscreen():
        with term.hidden_cursor():
            with term.cbreak():
                while True:
                    try:
                        _credits(term)
                        return
                    except ResizeScreenError:
                        pass
开发者ID:digideskio,项目名称:asciimatics,代码行数:16,代码来源:not_curses.py

示例7: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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()
开发者ID:thomasballinger,项目名称:blessed,代码行数:51,代码来源:keymatrix.py

示例8: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def main():
    term = Terminal()
    style = Style(heading=term.magenta,
                  hint=term.bright_cyan,
                  delimiter=u'|',
                  ) if term.number_of_colors else Style()
    screen = Screen(term, style)
    character_factory = WcWideCharacterGenerator
    pager = Pager(term, screen, character_factory)
    if term.is_a_tty:
        signal.signal(signal.SIGWINCH, pager.on_resize)
    else:
        screen.style.name_len = 80 - 15
        pager.dirty = 2
    with term.location(), term.cbreak(), term.fullscreen():
        pager.run(writer=echo, reader=term.inkey)
开发者ID:thomasballinger,项目名称:wcwidth,代码行数:18,代码来源:wcwidth-browser.py

示例9: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [as 别名]
def main(opts):
    """Program entry point."""
    term = Terminal()
    style = Style()

    # if the terminal supports colors, use a Style instance with some
    # standout colors (magenta, cyan).
    if term.number_of_colors:
        style = Style(attr_major=term.magenta, attr_minor=term.bright_cyan, alignment=opts["--alignment"])
    style.name_len = term.width - 15

    screen = Screen(term, style, wide=opts["--wide"])
    pager = Pager(term, screen, opts["character_factory"])

    with term.location(), term.cbreak(), term.fullscreen(), term.hidden_cursor():
        pager.run(writer=echo, reader=term.inkey)
    return 0
开发者ID:jquast,项目名称:wcwidth,代码行数:19,代码来源:wcwidth-browser.py

示例10: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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()
开发者ID:sfrapoport,项目名称:python-shell,代码行数:45,代码来源:shell_blessed.py

示例11: BrowseRouters

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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)]
#.........这里部分代码省略.........
开发者ID:jordant,项目名称:akanda-rug,代码行数:103,代码来源:browse.py

示例12: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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')))
开发者ID:jquast,项目名称:blessed,代码行数:98,代码来源:worms.py

示例13: Console

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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
#.........这里部分代码省略.........
开发者ID:robertfoss,项目名称:esp8266_apa102_bulb,代码行数:103,代码来源:Console.py

示例14: monitor

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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)
开发者ID:Koed00,项目名称:django-q,代码行数:86,代码来源:monitor.py

示例15: monitor

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import cbreak [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)
开发者ID:KorayAgaya,项目名称:django-q,代码行数:73,代码来源:monitor.py


注:本文中的blessed.Terminal.cbreak方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。