def __init__(self, executable='vim', args=None, env=None, encoding='utf-8', size=(80, 24), timeout=0.25): """ :param string executable: command name to execute *Vim* :param args: arguments to execute *Vim* :type args: None or string or list of string :param env: environment variables to execute *Vim* :type env: None or dict of (string, string) :param string encoding: internal encoding of *Vim* :param size: (lines, columns) of a screen connected to *Vim* :type size: (int, int) :param float timeout: seconds to wait I/O """ parser = arguments.Parser(self.default_args) args = parser.parse(args) self._process = process.Process(executable, args, env) self._encoding = encoding self._screen = pyte.Screen(*size) self._stream = pyte.Stream() self._stream.attach(self._screen) self._timeout = timeout self._tempfile = tempfile.NamedTemporaryFile(mode='r') self._runtimepath = None self.wait()
def test_ensure_width(monkeypatch): screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) escape = dict(pyte.Stream.escape) escape.update({"N": "next_page", "P": "prev_page"}) monkeypatch.setattr(pyte.Stream, "escape", escape) stream = pyte.Stream(screen) for idx in range(len(screen.buffer) * 5): stream.feed(str(idx) + os.linesep) assert screen.display == ["21 ", "22 ", "23 ", "24 ", " "] # a) shrinking the screen, expecting the lines displayed to # be truncated. screen.resize(5, 2) stream.feed(ctrl.ESC + "P") assert all(len(l) != 2 for l in screen.history.top) assert all(len(l) == 2 for l in screen.history.bottom) assert screen.display == ["18", "19", "20", "21", "22"] # b) expading the screen, expecting the lines displayed to # be filled with whitespace characters. screen.resize(5, 10) stream.feed(ctrl.ESC + "N") assert all(len(l) == 10 for l in list(screen.history.top)[-3:]) assert all(len(l) != 10 for l in screen.history.bottom) assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ]
def __init__(self, cmd, cols=80, lines=24, env={}, valgrind=None): self.cols = cols self.lines = lines self.screen = pyte.Screen(cols, lines) self.stream = pyte.Stream(self.screen) self.stream.use_utf8 = False self.p_pid, self.master_fd = pty.fork() if self.p_pid == 0: #Child if valgrind is not None: args = ['valgrind', '--log-file=%s' % valgrind] + cmd.split() efile = which('valgrind') else: args = cmd.split() efile = args[0] ENV = dict(os.environ) ENV.update( dict( TERM="xterm", COLUMNS=str(cols), LINES=str(lines), LANG='C', )) ENV.update(env) os.execve(efile, args, ENV) else: self.master_file = os.fdopen(self.master_fd, 'wb', 0) self.pid = self.p_pid
def test__buffer_hidden_cursor(self): """Ensure hidden cursor don't appear in the buffer return by _redraw_buffer Ensure that only one cursor is present in the buffer""" # '\u001b[?25h' : display cursor # '\u001b[?25l' : hide cursor escape_sequences = [ '\u001b[?25ha', '\r\n\u001b[?25lb', '\r\n\u001b[?25hc', ] screen = pyte.Screen(80, 24) stream = pyte.Stream(screen) def hidden_cursor(x, y): c = pyte.screens.Cursor(x, y) c.hidden = True return c expected_cursors = [ pyte.screens.Cursor(1, 0), hidden_cursor(1, 1), pyte.screens.Cursor(1, 2), ] z = itertools.zip_longest(expected_cursors, escape_sequences) cursor = None for count, (expected_cursor, escape_sequence) in enumerate(z): with self.subTest(case='Hidden cursor - item #{}'.format(count)):
def __terminal(self, evt): w, h = self.GetSize() self.__buffer = wx.EmptyBitmap(w, h) self.__clear_buffer() self.__stream = pyte.Stream() self.__screen = _Terminal(w / self.__col_width, h / self.__line_height) self.__stream.attach(self.__screen) self.__reset() #self.__resize(w, h) self.Bind(wx.EVT_PAINT, self.__on_paint) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None) self.Bind(wx.EVT_SIZE, self.__on_size) self.Bind(wx.EVT_CHAR, self.__on_char) self.Bind(wx.EVT_KILL_FOCUS, self.__on_kill_focus) self.Bind(wx.EVT_SET_FOCUS, self.__on_set_focus) self.Bind(wx.EVT_LEFT_DOWN, self.__on_leftdown) self.Bind(wx.EVT_LEFT_UP, self.__on_leftup) self.Bind(wx.EVT_MIDDLE_DOWN, self.__on_middledown) self.Bind(wx.EVT_LEFT_DCLICK, self.__on_leftdclick) self.Bind(wx.EVT_MOTION, self.__on_motion) #print [a for a in dir(self) if 'focus' in a.lower()] self.__has_focus = self.FindFocus() is self
def __init__(self, size_x, size_y, display_q): super(DisplayThread, self).__init__() self.display_q = display_q self.bus = 0 self.device = 0 self.x_max = 128 self.y_max = 296 self.size_x = size_x self.size_y = size_y self.stoprequest = threading.Event() self.epd = epd2in9.EPD() self.epd.init(self.epd.lut_full_update) self.image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH), 255) self.font = ImageFont.load('terminus_12.pil') self.line_height = 16 #self.font = ImageFont.truetype('terminus.ttf', 12) self.draw = ImageDraw.Draw(self.image) self.clear_display() self.clear_display() self.epd.init(self.epd.lut_partial_update) self.screen = pyte.Screen(self.size_x, self.size_y) self.stream = pyte.Stream(self.screen) self.buffer = [] self.cursor_enabled = False
def __init__(self, width=None): self.width = width or self.BIG self.screen = Screen(lines=self.BIG, columns=self.width, line_buffer=self) self.stream = pyte.Stream(screen=self.screen) self.max_line = -1 self.raw_to_self = {} self.self_to_raw = {}
def __phase4(self, infile): logger.info('=== STARTING PHASE 4 SESSION EXECUTION ===') screen = pyte.Screen(80, 25) stream = pyte.Stream(screen) results = {} next_token = '[get-seed' with open(infile, 'r') as input_data: lines = input_data.readlines() seed_start_pos = 0 current_junc = '' for idx, line in enumerate(lines): if next_token in line: current_junc = line.split('-')[2].split(']')[0] next_token = '[get-timings' seed_start_pos = idx break count = len(lines) - seed_start_pos for idx, line in enumerate(lines[seed_start_pos:]): if next_token in line: next_token = self.__swap_seed_tokens(next_token) current_screen = '\n'.join(screen.display) if not current_junc in results: results[current_junc] = self.__create_entry() self.__extract_data_from_screen(current_screen, next_token, current_junc, results) screen.reset() current_junc = line.split('-')[2].split(']')[0] logger.debug('[{:05.2f}%] We are at {}'.format(100 * idx / count, current_junc)) stream.feed(line) current_screen = '\n'.join(screen.display) self.__extract_data_from_screen(current_screen, next_token, current_junc, results) screen.reset() logger.info('=== PHASE 4 SESSION DONE ===') return results
def test_ensure_width(monkeypatch): screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) escape = dict(pyte.Stream.escape) escape.update({"N": "next_page", "P": "prev_page"}) monkeypatch.setattr(pyte.Stream, "escape", escape) stream = pyte.Stream(screen) for idx in range(screen.lines * 5): stream.feed("{0:04d}".format(idx) + os.linesep) assert screen.display == ["0021 ", "0022 ", "0023 ", "0024 ", " "] # Shrinking the screen should truncate the displayed lines following lines. screen.resize(5, 3) stream.feed(ctrl.ESC + "P") # Inequality because we have an all-empty last line. assert all(len(l) <= 3 for l in screen.history.bottom) assert screen.display == [ "001", # 18 "001", # 19 "002", # 20 "002", # 21 "002" # 22 ]
def __init__(self, manager=None, id=None, command=None, autoclose=False, autoclose_retain=5): self.width = 80 self.height = 25 self.id = id self.manager = manager self.autoclose = autoclose self.autoclose_retain = autoclose_retain self.output = BroadcastQueue() env = {} env.update(os.environ) env['TERM'] = 'linux' env['COLUMNS'] = str(self.width) env['LINES'] = str(self.height) env['LC_ALL'] = 'en_US.UTF8' self.command = command if not self.command: shell = os.environ.get('SHELL', None) if not shell: for sh in ['zsh', 'bash', 'sh']: try: shell = subprocess.check_output(['which', sh]) break except: pass self.command = shell args = ['sh', '-c', self.command] exe = 'sh' logging.info('Activating new terminal: %s', self.command) self.pid, self.fd = pty.fork() if self.pid == 0: setproctitle.setproctitle('%s terminal session #%i' % (sys.argv[0], os.getpid())) os.execvpe(exe, args, env) logging.info('Subprocess PID %s', self.pid) self.dead = False fl = fcntl.fcntl(self.fd, fcntl.F_GETFL) fcntl.fcntl(self.fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) self.stream_in = os.fdopen(self.fd, 'rb', 0) self.stream_out = os.fdopen(self.fd, 'wb', 0) self.pyte_stream = pyte.Stream() self.screen = pyte.DiffScreen(self.width, self.height) self.pyte_stream.attach(self.screen) self.last_cursor_position = None self.reader = gevent.spawn(self.reader_fn)
def __init__(self, sid=''): # self.out = sids[sid].before.replace('\r\r\n', '').split('\r\n') # return if pyte_ok: screen = pyte.Screen(os.get_terminal_size()[0], max_lines) stream = pyte.Stream(screen) screen.mode.add(pyte.modes.LNM) ss = sids[sid].before.replace('\r\r\n', '').replace('\r\n', 'CRNL') stream.feed(ss) self.out = [ i.rstrip() for i in ''.join(screen.display).split('CRNL') ] del screen, stream else: l, s, r = sids[sid].before.replace('\r\r\n', '').rpartition('\x1b') if l == '': l, s, r = sids[sid].before.replace('\r\r\n', '').partition('\r\n') else: l1, s, r = r.partition('\r\n') term = ANSI.ANSI(*os.get_terminal_size()[::-1]) term.process_list(l) self.out = [(''.join(str(term).split('\n'))).strip() ] + r.split('\r\n')
def reset(self, restart=True): if restart: self._push_action(" ") self._push_action("\r\n") self._push_action("^C") os.kill(self.p_pid, signal.SIGTERM) os.close(self.master_fd) os.waitpid(self.p_pid, 0) p_pid, master_fd = pty.fork() if p_pid == 0: # Child. os.execvpe(executable, [executable], env=dict(TERM="linux", COLUMNS="80", LINES="24")) os.exit(0) else: self.p_pid = p_pid self.screen = pyte.Screen(80, 24) self.stream = pyte.Stream(self.screen) self.master_fd = master_fd self.state_history.clear() self.scores += [0] time.sleep(0.1) obs = self.get_frame() return np.zeros([SCREEN_HEIGHT, SCREEN_WIDTH, len(self.CHAR_BINS)])
def test__buffer_simple_events(self): escape_sequences = ['{}\r\n'.format(i) for i in range(5)] screen = pyte.Screen(80, 24) stream = pyte.Stream(screen) for count, escape_sequence in enumerate(escape_sequences): with self.subTest(case='Simple events (record #{})'.format(count)): stream.feed(escape_sequence)
def __init__(self): # Initialize the pyte screen based on the current screen size # noinspection PyUnresolvedReferences self.screen = pyte.screens.DiffScreen(*_stash.terminal.get_wh()) self.stream = pyte.Stream() self.stream.attach(self.screen) self.client = None
def test_non_utf8_shifts(): screen = pyte.Screen(3, 3) handler = screen.shift_in = screen.shift_out = argcheck() stream = pyte.Stream(screen) stream.use_utf8 = False stream.feed(ctrl.SI) stream.feed(ctrl.SO) assert handler.count == 2
def __init__(self): self.ssh_running = False self.screen = pyte.screens.DiffScreen(100, 60) self.screen.dirty.clear() #self.screen.set_mode(pyte.modes.DECTCEM) self.stream = pyte.Stream() self.stream.attach(self.screen) self.pause_output = False
def test_dollar_skip(): screen = pyte.Screen(3, 3) handler = screen.draw = argcheck() stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "12$p") assert handler.count == 0 stream.feed(ctrl.CSI + "1;2;3;4$x") assert handler.count == 0
def test_overflow(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "999999999999999;99999999999999" + esc.HVP) assert handler.count == 1 assert handler.args == (9999, 9999)
def test_missing_params(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + ";" + esc.HVP) assert handler.count == 1 assert handler.args == (0, 0)
def __init__(self): # Initialize the pyte screen based on the current screen size # noinspection PyUnresolvedReferences self.screen = pyte.screens.DiffScreen(*_stash.terminal.get_wh()) self.stream = pyte.Stream() self.stream.attach(self.screen) self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def _get_output_lines(script, log_file): lines = log_file.readlines()[-const.LOG_SIZE:] grouped = list(_group_by_calls(lines)) script_lines = _get_script_group_lines(grouped, script) screen = pyte.Screen(get_terminal_size().columns, len(script_lines)) stream = pyte.Stream(screen) stream.feed(''.join(script_lines)) return screen.display
def test_private_report_device_attributes(): # Some console apps (e.g. ADOM) might add ``?`` to the DA request, # even though the VT102/VT220 spec does not allow this. screen = pyte.Screen(10, 10) stream = pyte.Stream(screen) acc = [] screen.write_process_input = acc.append stream.feed(ctrl.CSI + "?0c") assert acc.pop() == ctrl.CSI + "?6c"
def test_control_characters(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "10;\t\t\n\r\n10" + esc.HVP) assert handler.count == 1 assert handler.args == (10, 10)
def _get_output_lines(script, log_file): data = log_file.read().decode() data = re.sub(r'\x00+$', '', data) lines = data.split('\n') grouped = list(_group_by_calls(lines)) script_lines = _get_script_group_lines(grouped, script) screen = pyte.Screen(get_terminal_size().columns, len(script_lines)) stream = pyte.Stream(screen) stream.feed('\n'.join(script_lines)) return screen.display
def test_unknown_sequences(): handler = argcheck() screen = pyte.Screen(80, 24) screen.debug = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "6;Z") assert handler.count == 1 assert handler.args == (6, 0) assert handler.kwargs == {}
def test_linefeed(): # ``linefeed`` is somewhat an exception, there's three ways to # trigger it. handler = counter() screen = pyte.Screen(80, 24) screen.linefeed = handler stream = pyte.Stream(screen) stream.feed(ctrl.LF + ctrl.VT + ctrl.FF) assert handler.count == 3
def test_input_output(name): with open(os.path.join(captured_dir, name + ".input"), "rb") as handle: input = handle.read() with open(os.path.join(captured_dir, name + ".output")) as handle: output = json.load(handle) screen = pyte.Screen(80, 24) stream = pyte.Stream(screen) stream.feed(input) assert screen.display == output
def _init_connection(self) -> None: """Opens a connection and intializes variables.""" try: self.proc = pwn.remote(self.ip, self.PORT) except pwn.pwnlib.exception.PwnlibException: # Raising a ConnectionRefusedError here is not necessarily correct. # Anyway, this error is handled by the checkerlib. raise ConnectionRefusedError("Cannot connect to target") self.screen = pyte.Screen(40, 20) self.stream = pyte.Stream(self.screen, True)
def test_non_csi_sequences(): for cmd, event in pyte.Stream.csi.items(): # a) single param handler = argcheck() screen = pyte.Screen(80, 24) setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.ESC + "[5" + cmd) assert handler.count == 1 assert handler.args == (5, ) # b) multiple params, and starts with CSI, not ESC [ handler = argcheck() screen = pyte.Screen(80, 24) setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "5;12" + cmd) assert handler.count == 1 assert handler.args == (5, 12)
def test_basic_sequences(): for cmd, event in pyte.Stream.escape.items(): screen = pyte.Screen(80, 24) handler = counter() setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.ESC) assert not handler.count stream.feed(cmd) assert handler.count == 1, event