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


Python Terminal.location方法代码示例

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


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

示例1: main

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

示例2: participant_context

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [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']
开发者ID:hsharrison,项目名称:bistable-perception-experiment,代码行数:36,代码来源:experiment.py

示例3: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [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

示例4: start

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
    def start(self):
        path = self.generate()
        web.path = path
        if web.payloads is not None:
            if self.dbms:
                if self.dbms == 'Mongo':
                    cmd = "run -id -p {0}:80 -v {1}:{2}:rw -v {3}:/etc/php5/fpm/php.ini:ro -v {4}:/usr/lib/php5/modules/mongodb.so:ro --link {5}:{6} --name VW --workdir {2} {7} ".format(
                        self.expose, web.path, self.mount_point, os.path.join(web.path, 'php.ini'), os.path.join(web.path, 'mongodb.so'), web.container_name, self.dbms.lower(), self.image)
                else:
                    cmd = "run -id -p {0}:80 -v {1}:{2} -v {3}:/etc/php5/fpm/php.ini --link {4}:{5} --name VW --workdir {2} {6} ".format(
                        self.expose, web.path, self.mount_point, os.path.join(web.path, 'php.ini'), web.container_name, self.dbms.lower(), self.image)
                if self.command:
                    cmd = cmd + self.command
                web.dAgent.send(cmd)
            else:
                cmd = "run -id -p {0}:80 -v {1}:{2}:rw -v {3}:/etc/php5/fpm/php.ini:ro --name VW --workdir {2} {4} ".format(
                    self.expose, web.path, self.mount_point, os.path.join(web.path, 'php.ini'), self.image)
                if self.command:
                    cmd = cmd + self.command
                web.dAgent.send(cmd)
            web.ctr = web.dAgent.recv()

            if "cmd" in web.payloads:
                Logger.logInfo(
                    "[INFO] " + "CMD: {0}".format(web.payloads['cmd']))
                web.dAgent.send(
                    "exec {0} -- {1}".format(web.ctr, web.payloads['cmd']))
            if "warning" in web.payloads:
                for warning in web.payloads['warning']:
                    Logger.logWarning("[WARNING] " + warning)
            if "error" in web.payloads:
                for error in web.payloads['error']:
                    Logger.logError("[ERROR] " + error)

            url = ['http', '127.0.0.1:{0}'.format(
                self.expose), '/', '', '', '']
            params = {}

            if web.payloads['key'] is not None:
                for index, _ in enumerate(web.payloads['key']):
                    if re.search("page", web.payloads['key'][index], flags=re.IGNORECASE):
                        web.payloads['value'][index] = "index"
                    params.update({'{0}'.format(web.payloads['key'][index]): '{0}'.format(
                        web.payloads['value'][index])})

            query = params

            url[4] = urlencode(query)

            t = Terminal()
            with t.location(0, t.height - 1):
                Logger.logSuccess(
                    t.center(t.blink("Browse: {0}".format(urlparse.urlunparse(url)))))

            web.dAgent.send("logs {0} -f".format(web.ctr))
开发者ID:qazbnm456,项目名称:VWGen,代码行数:57,代码来源:VWGen.py

示例5: run_8

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def run_8():
    term = Terminal()
    current_loc = (10, 10)
    loop = asyncio.get_event_loop()
    while True:
        future = asyncio.Future()
        asyncio.ensure_future(handle_keyboard_input(future, term))
        loop.run_until_complete(future)
        move_where = process_result(future.result(), term)
        current_loc = (sum(x) for x in zip(current_loc, move_where))
        with term.fullscreen(), term.location(*current_loc):
            print(move_where)
开发者ID:jbwincek,项目名称:Plie,代码行数:14,代码来源:event_handler_mockups.py

示例6: run_7

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def run_7():
    term = Terminal()
    loop = asyncio.get_event_loop()
    #renderer = plie.Renderer(view=test_view)
    current_loc = (10,10)
    with term.fullscreen():
        while True:
            #renderer.display()
            future = asyncio.Future()
            asyncio.ensure_future(handle_keyboard_input(future, term))
            loop.run_until_complete(future)
            current_loc = process_result(future.result(), term, current_loc)
            with term.location(*current_loc):
                print('x',end='')
开发者ID:jbwincek,项目名称:Plie,代码行数:16,代码来源:event_handler_mockups.py

示例7: display_response_scale

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def display_response_scale(term: Terminal, response_type: str, value: float, draw_arrows=True):
    figlet_width = int(term.width // FIGLET_SCALE_FACTOR)
    # We need an odd width so that the cursor can be centered.
    width = figlet_width if figlet_width % 2 else figlet_width - 1
    float_idx = 1 + (width - 2) * (value + 1) / 2
    idx = ceil(float_idx) if float_idx < 0 else floor(float_idx)

    scale = width * ['-']
    scale[idx - 1:idx + 2] = ['|', 'x', '|']
    figlet_scale = figlet(''.join(scale), width=term.width)
    figlet_scale = '\n'.join(line + (term.width - len(line)) * ' ' for line in figlet_scale.split('\n'))

    effective_width = width * FIGLET_SCALE_FACTOR
    x_margin = int((term.width - effective_width) // 2)

    scale_y = int(2 * term.height // 3) - 1
    multiline_print_at_location(term, figlet_scale, x_margin, scale_y)

    if draw_arrows:
        left_arrow = figlet('<<=')
        right_arrow = figlet('=>>')
        arrow_width = len(left_arrow.split('\n')[0])

        arrow_y = int(term.height // 3)
        left_arrow_x = x_margin + int(effective_width // 4 - arrow_width // 2)
        multiline_print_at_location(term, left_arrow, left_arrow_x, arrow_y)

        label_y = arrow_y - 1
        with term.location(left_arrow_x - 8, label_y):
            print("Looks {}like a woman's figure.".format('more ' if response_type == 'continuous' else ''))

        right_arrow_x = x_margin + int(3 * effective_width // 4 - arrow_width // 2)
        multiline_print_at_location(term, right_arrow, right_arrow_x, arrow_y)

        right_message = "Looks {}like a man's face.".format('more ' if response_type == 'continuous' else '')
        with term.location(right_arrow_x - 5, label_y):
            print(right_message)
开发者ID:hsharrison,项目名称:bistable-perception-experiment,代码行数:39,代码来源:experiment.py

示例8: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [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

示例9: main

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

示例10: start

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
    def start(self):
        path = self.generate()
        web.path = path
        if web.payloads is not None:
            web.ctr = web.dAgent.startContainer(image='{0}'.format(self.image), ports=[80], volumes=['{0}'.format(self.mount_point), '/etc/php5/fpm/php.ini'],
                                                      host_config=web.dAgent.createHostConfig(
                port_bindings={
                    80: self.expose
                },
                binds=self.bindsOperation(),
                links={'{0}'.format(web.container_name): '{0}'.format(
                    self.dbms.lower())} if self.dbms is not None else None
            ), name='VW')

            if "cmd" in web.payloads:
                Logger.logInfo(
                    "[INFO] " + "CMD: cd {0} && {1}".format(self.mount_point, web.payloads['cmd']))
                web.dAgent.execute(web.ctr, web.payloads[
                                   'cmd'], self.mount_point)

            if "warning" in web.payloads:
                for warning in web.payloads['warning']:
                    Logger.logWarning("[WARNING] " + warning)
            if "error" in web.payloads:
                for error in web.payloads['error']:
                    Logger.logError("[ERROR] " + error)

            url = ['http', '{0}:{1}'.format(
                web.dAgent.host, self.expose), '/', '', '', '']
            params = {}

            if web.payloads['key'] is not None:
                for index, _ in enumerate(web.payloads['key']):
                    if re.search("page", web.payloads['key'][index], flags=re.IGNORECASE):
                        web.payloads['value'][index] = "index"
                    params.update({'{0}'.format(web.payloads['key'][index]): '{0}'.format(
                        web.payloads['value'][index])})

            query = params

            url[4] = urlencode(query)

            t = Terminal()
            with t.location(0, t.height - 1):
                Logger.logSuccess(
                    t.center(t.blink("Browse: {0}".format(urlparse.urlunparse(url)))))

            web.dAgent.logs(web.ctr)
开发者ID:MahaKoala,项目名称:VWGen,代码行数:50,代码来源:VWGen.py

示例11: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [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

示例12: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [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

示例13: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def main():
    words = ["exit", "select", "deselect", "status", "timeline", "readstream", 
        "oracle", "jobmanager",
        "cuttsum.trecdata.UrlListResource", "cuttsum.trecdata.SCChunkResource"]
    completer = Completer(words)
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer.complete)
    active_events = []
    all_events = cuttsum.events.get_events() 
    for e in all_events:
        print e.query_num
    t = Terminal()

    with t.fullscreen():
        while 1:
            home_screen(t, active_events)
            with t.location(0, t.height-1):
                cmd = raw_input(">>> ")
            args = cmd.split(" ")

            if args[0] == "select" and len(args) >= 2:
                cmd_select_events(
                    args[1:], active_events, all_events)
            elif args[0] == "deselect" and len(args) >= 2:
                active_events = cmd_deselect_events(
                    args[1:], active_events)
            elif args[0] == "timeline":
                print_event_timelines(t, active_events)
            elif args[0] == "status":
                cmd_status(args[1:], t, active_events)
            elif args[0] == "run":
                cmd_run(args[1:], t, active_events)

            elif args[0] == "readstream":
                cmd_readstream(args[1:], t, active_events)
            elif args[0] == "oracle":
                cmd_oracle(args[1:], t, active_events)
            elif args[0] == "jobmanager":
                from app.job_manager import start_job_manager
                start_job_manager(args[1:], t, active_events)
            elif args[0] == "exit":
                break
开发者ID:kedz,项目名称:cuttsum,代码行数:44,代码来源:trec-info.py

示例14: main

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def main():
    """Program entry point."""
    # pylint: disable=invalid-name
    #         Invalid variable name "Position"
    Position = collections.namedtuple('Position', ('row', 'column'))

    # particularly strange, we use sys.stderr as our output stream device,
    # this 'stream' file descriptor is only used for side effects, of which
    # this application uses two: the term.location() has an implied write,
    # as does get_position().
    #
    # the reason we chose stderr is to ensure that the terminal emulator
    # receives our bytes even when this program is wrapped by shell eval
    # `resize.py`; backticks gather stdout but not stderr in this case.
    term = Terminal(stream=sys.stderr)

    # Move the cursor to the farthest lower-right hand corner that is
    # reasonable.  Due to word size limitations in older protocols, 999,999
    # is our most reasonable and portable edge boundary.  Telnet NAWS is just
    # two unsigned shorts: ('!HH' in python struct module format).
    with term.location(999, 999):

        # We're not likely at (999, 999), but a well behaved terminal emulator
        # will do its best to accommodate our request, positioning the cursor
        # to the farthest lower-right corner.  By requesting the current
        # position, we may negotiate about the window size directly with the
        # terminal emulator connected at the distant end.
        pos = Position(*term.get_location(timeout=5.0))

        if -1 not in pos:
            # true size was determined
            lines, columns = pos.row, pos.column

        else:
            # size could not be determined. Oh well, the built-in blessed
            # properties will use termios if available, falling back to
            # existing environment values if it has to.
            lines, columns = term.height, term.width

    print("COLUMNS={columns};\nLINES={lines};\nexport COLUMNS LINES;"
          .format(columns=columns, lines=lines))
开发者ID:cjfuller,项目名称:blessed,代码行数:43,代码来源:resize.py

示例15: ask_key

# 需要导入模块: from blessed import Terminal [as 别名]
# 或者: from blessed.Terminal import location [as 别名]
def ask_key():
    if Terminal is None:
        try:
            value = raw_input(
                "Type the decryption key, "
                "without spaces or other special characters: ")
            return value.strip().decode('hex')
        except TypeError:
            return None
    sys.__stdin__ = sys.stdin
    t = Terminal()
    width = 64
    lwidth = 16
    movement = {
        'KEY_LEFT': -1,
        'KEY_RIGHT': 1,
        'KEY_UP': -lwidth,
        'KEY_DOWN': lwidth,
        'KEY_HOME': -width,
        'KEY_END': width,
        'KEY_BACKSPACE': -1
    }

    value = [" "] * width
    rows = ["B", "C", "D", "E"]

    def valid():
        return " " not in value

    with t.cbreak():
        val = None
        validvalue = None
        pos = 0
        nrows = width/lwidth
        print "Type the decryption key, or press 'q' to cancel"
        while val not in (u'q', u'Q',):
            for i in range(width/lwidth):
                s = lwidth / 2
                print rows[i],
                print t.underline("".join(value[2*i*s:(2*i+1)*s])),
                print t.underline("".join(value[(2*i+1)*s:(2*i+2)*s]))
            if valid():
                print "key valid, press enter to accept"
            else:
                print t.clear_eol
            if validvalue is not None:
                break
            sys.stdout.write(t.move_up * (nrows+1))
            with t.location():
                y = pos/lwidth
                x = pos % lwidth
                sys.stdout.write(t.move_down * y)
                sys.stdout.write(t.move_right * (x + 2 + (2*x)/lwidth))
                sys.stdout.flush()
                val = t.inkey(timeout=5)
                if not val:
                    pass
                elif val.is_sequence:
                    if val.name in movement:
                        newpos = pos + movement[val.name]
                        pos = min(width-1, max(0, newpos))
                    if val.name in ('KEY_DELETE', 'KEY_BACKSPACE'):
                        value[pos:width] = value[pos+1:width] + [" "]
                    elif val.name is 'KEY_ENTER' and valid():
                        validvalue = value
                elif val.lower() in "0123456789abcdef":
                    if pos < width:
                        value[pos] = val.upper()
                        if pos < width - 1:
                            pos += 1
    if validvalue is not None:
        return ("".join(validvalue)).decode('hex')
    return validvalue
开发者ID:longaccess,项目名称:longaccess-client,代码行数:75,代码来源:certinput.py


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