Python termios.TIOCSWINSZ Examples

The following are 30 code examples of termios.TIOCSWINSZ(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module termios , or try the search function .
Example #1
Source File: __init__.py    From camr with GNU General Public License v2.0 7 votes vote down vote up
def setwinsize(self, rows, cols):

        '''This sets the terminal window size of the child tty. This will cause
        a SIGWINCH signal to be sent to the child. This does not change the
        physical window size. It changes the size reported to TTY-aware
        applications like vi or curses -- applications that respond to the
        SIGWINCH signal. '''

        # Some very old platforms have a bug that causes the value for
        # termios.TIOCSWINSZ to be truncated. There was a hack here to work
        # around this, but it caused problems with newer platforms so has been
        # removed. For details see https://github.com/pexpect/pexpect/issues/39
        TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
        # Note, assume ws_xpixel and ws_ypixel are zero.
        s = struct.pack('HHHH', rows, cols, 0, 0)
        fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) 
Example #2
Source File: terminal.py    From ashier with Apache License 2.0 6 votes vote down vote up
def MatchWindowSize(master, slave):
  """Keep window sizes of two terminals in sync.

  Copy window size information from one terminal to another and
  register a signal hander to update window size information on
  the second terminal when window size of the first changes.

  Args:
    master: file descriptor of the terminal to observe.
    slave: file descriptor of the terminal to update.

  Returns:
    None.
  """

  def _CopyWindowSize():
    window_size = fcntl.ioctl(master, termios.TIOCGWINSZ, '00000000')
    fcntl.ioctl(slave, termios.TIOCSWINSZ, window_size)
    signal.signal(signal.SIGWINCH, lambda s, f: _CopyWindowSize())

  _CopyWindowSize() 
Example #3
Source File: test_ioctl.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_ioctl_signed_unsigned_code_param(self):
        if not pty:
            raise TestSkipped('pty module required')
        mfd, sfd = pty.openpty()
        try:
            if termios.TIOCSWINSZ < 0:
                set_winsz_opcode_maybe_neg = termios.TIOCSWINSZ
                set_winsz_opcode_pos = termios.TIOCSWINSZ & 0xffffffffL
            else:
                set_winsz_opcode_pos = termios.TIOCSWINSZ
                set_winsz_opcode_maybe_neg, = struct.unpack("i",
                        struct.pack("I", termios.TIOCSWINSZ))

            # We're just testing that these calls do not raise exceptions.
            saved_winsz = fcntl.ioctl(mfd, termios.TIOCGWINSZ, "\0"*8)
            our_winsz = struct.pack("HHHH",80,25,0,0)
            # test both with a positive and potentially negative ioctl code
            new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_pos, our_winsz)
            new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, our_winsz)
            fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, saved_winsz)
        finally:
            os.close(mfd)
            os.close(sfd) 
Example #4
Source File: subprocess.py    From tbot with GNU General Public License v3.0 5 votes vote down vote up
def update_pty(self, columns: int, lines: int) -> None:
        s = struct.pack("HHHH", lines, columns, 0, 0)
        fcntl.ioctl(self.pty_master, termios.TIOCSWINSZ, s, False) 
Example #5
Source File: terminal.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _setwinsize(fd, rows, cols):
    # Some very old platforms have a bug that causes the value for
    # termios.TIOCSWINSZ to be truncated. There was a hack here to work
    # around this, but it caused problems with newer platforms so has been
    # removed. For details see https://github.com/pexpect/pexpect/issues/39
    TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
    # Note, assume ws_xpixel and ws_ypixel are zero.
    s = struct.pack('HHHH', rows, cols, 0, 0)
    fcntl.ioctl(fd, TIOCSWINSZ, s) 
Example #6
Source File: TerminalProcess.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def resize(self, rows, cols):
		if (self.rows == rows) and (self.cols == cols):
			return

		self.rows = rows
		self.cols = cols
		self.term.resize(self.rows, self.cols)

		if not self.completed:
			fcntl.ioctl(self.data_pipe, termios.TIOCSWINSZ, struct.pack("hhhh", self.rows, self.cols, 0, 0)) 
Example #7
Source File: TerminalProcess.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def restart(self, cmd):
		if not self.completed:
			self.process_input("\n\033[01;31mProcess killed.\033[00m\r\n")
			os.kill(self.pid, signal.SIGHUP)
			thread = self.thread
			thread.stop()
			while thread.alive:
				QCoreApplication.processEvents()

		self.exit_pipe, child_pipe = os.pipe()
		pid, fd = pty.fork()
		if pid == 0:
			try:
				os.environ["TERM"] = "xterm-256color"
				retval = subprocess.call(cmd, close_fds=True)
				os.write(2, "\033[01;34mProcess has completed.\033[00m\n")
				os.write(child_pipe, "t")
				os._exit(retval)
			except:
				pass
			os.write(2, "\033[01;31mCommand '" + cmd[0] + "' failed to execute.\033[00m\n")
			os.write(child_pipe, "f")
			os._exit(1)

		os.close(child_pipe)
		self.process_input("\033[01;34mStarted process with PID %d.\033[00m\r\n" % pid)

		self.pid = pid
		self.data_pipe = fd
		self.completed = False

		# Initialize terminal settings
		fcntl.ioctl(self.data_pipe, termios.TIOCSWINSZ, struct.pack("hhhh", self.rows, self.cols, 0, 0))
		attribute = termios.tcgetattr(self.data_pipe)
		termios.tcsetattr(self.data_pipe, termios.TCSAFLUSH, attribute)

		self.thread = TerminalUpdateThread(self, self.data_pipe, self.exit_pipe)
		self.thread.start() 
Example #8
Source File: __init__.py    From enlighten with Mozilla Public License 2.0 5 votes vote down vote up
def resize(self, height, width):
        fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('hhhh', height, width, 0, 0)) 
Example #9
Source File: vterm.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def set_termsize(self, width, height):
        winsize = struct.pack("HHHH", height, width, 0, 0)
        fcntl.ioctl(self.master, termios.TIOCSWINSZ, winsize) 
Example #10
Source File: test_length_sequence.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_Sequence_alignment(all_terms, many_lines):
    """Tests methods related to Sequence class, namely ljust, rjust, center."""
    @as_subprocess
    def child(kind, lines=25, cols=80):
        # set the pty's virtual window size
        val = struct.pack('HHHH', lines, cols, 0, 0)
        fcntl.ioctl(sys.__stdout__.fileno(), termios.TIOCSWINSZ, val)
        t = TestTerminal(kind=kind)

        pony_msg = 'pony express, all aboard, choo, choo!'
        pony_len = len(pony_msg)
        pony_colored = u''.join(
            ['%s%s' % (t.color(n % 7), ch,)
             for n, ch in enumerate(pony_msg)])
        pony_colored += t.normal
        ladjusted = t.ljust(pony_colored)
        radjusted = t.rjust(pony_colored)
        centered = t.center(pony_colored)
        assert (t.length(pony_colored) == pony_len)
        assert (t.length(centered.strip()) == pony_len)
        assert (t.length(centered) == len(pony_msg.center(t.width)))
        assert (t.length(ladjusted.strip()) == pony_len)
        assert (t.length(ladjusted) == len(pony_msg.ljust(t.width)))
        assert (t.length(radjusted.strip()) == pony_len)
        assert (t.length(radjusted) == len(pony_msg.rjust(t.width)))

    child(kind=all_terms, lines=many_lines) 
Example #11
Source File: logger.py    From conary with Apache License 2.0 5 votes vote down vote up
def _resizeTerminal(self):
        """ If a windowing system has announced to us that the window has
            been resized, pass that information to the pseudo tty so that
            output can be reformated
        """
        s = struct.pack('HHHH', 0, 0, 0, 0)
        result = fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, s)
        rows, cols = struct.unpack('HHHH', result)[0:2]
        s = struct.pack('HHHH', rows, cols, 0, 0)
        fcntl.ioctl(self.ptyFd, termios.TIOCSWINSZ, s) 
Example #12
Source File: logger.py    From conary with Apache License 2.0 5 votes vote down vote up
def _setTerminalSize(self, rows, cols):
        s = struct.pack('HHHH', rows, cols, 0, 0)
        fcntl.ioctl(self.ptyFd, termios.TIOCSWINSZ, s) 
Example #13
Source File: epdb_server.py    From conary with Apache License 2.0 5 votes vote down vote up
def process_IAC(self, sock, cmd, option):
        """
            Read in and parse IAC commands as passed by telnetlib.

            SB/SE commands are stored in sbdataq, and passed in w/ a command
            of SE.  
        """
        if cmd == DO:
            if option == TM: # timing mark - send WILL into outgoing stream
                os.write(self.remote, IAC + WILL + TM)
            else:
                pass
        elif cmd == IP:
            # interrupt process
            os.write(self.local, chr(ord('C') & 0x1F))
        elif cmd == SB:
            pass
        elif cmd == SE:
            option = self.sbdataq[0]
            if option == NAWS: # negotiate window size.
                cols = ord(self.sbdataq[1])
                rows = ord(self.sbdataq[2])
                s = struct.pack('HHHH', rows, cols, 0, 0)
                fcntl.ioctl(self.local, termios.TIOCSWINSZ, s)
        elif cmd == DONT:
            pass
        else:
            pass 
Example #14
Source File: epdb_server.py    From epdb with MIT License 5 votes vote down vote up
def process_IAC(self, sock, cmd, option):
        """
            Read in and parse IAC commands as passed by telnetlib.

            SB/SE commands are stored in sbdataq, and passed in w/ a command
            of SE.
        """
        if cmd == DO:
            if option == TM:
                # timing mark - send WILL into outgoing stream
                os.write(self.remote, IAC + WILL + TM)
            else:
                pass
        elif cmd == IP:
            # interrupt process
            os.write(self.local, IPRESP)
        elif cmd == SB:
            pass
        elif cmd == SE:
            option = self.sbdataq[0]
            if option == NAWS[0]:
                # negotiate window size.
                cols = six.indexbytes(self.sbdataq, 1)
                rows = six.indexbytes(self.sbdataq, 2)
                s = struct.pack('HHHH', rows, cols, 0, 0)
                fcntl.ioctl(self.local, termios.TIOCSWINSZ, s)
        elif cmd == DONT:
            pass
        else:
            pass 
Example #15
Source File: ptyprocess.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def _setwinsize(fd, rows, cols):
    # Some very old platforms have a bug that causes the value for
    # termios.TIOCSWINSZ to be truncated. There was a hack here to work
    # around this, but it caused problems with newer platforms so has been
    # removed. For details see https://github.com/pexpect/pexpect/issues/39
    TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
    # Note, assume ws_xpixel and ws_ypixel are zero.
    s = struct.pack('HHHH', rows, cols, 0, 0)
    fcntl.ioctl(fd, TIOCSWINSZ, s) 
Example #16
Source File: app.py    From pyxterm.js with MIT License 5 votes vote down vote up
def set_winsize(fd, row, col, xpix=0, ypix=0):
    winsize = struct.pack("HHHH", row, col, xpix, ypix)
    fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) 
Example #17
Source File: dispatchers.py    From polysh with GNU General Public License v2.0 5 votes vote down vote up
def update_terminal_size() -> None:
    """Propagate the terminal size to the remote shells accounting for the
    place taken by the longest name"""
    w, h = terminal_size()
    w = max(w - display_names.max_display_name_length - 2, min(w, 10))
    # python bug http://python.org/sf/1112949 on amd64
    # from ajaxterm.py
    bug = struct.unpack('i', struct.pack('I', termios.TIOCSWINSZ))[0]
    packed_size = struct.pack('HHHH', h, w, 0, 0)
    term_size = w, h
    for i in all_instances():
        if i.enabled and i.term_size != term_size:
            i.term_size = term_size
            fcntl.ioctl(i.fd, bug, packed_size) 
Example #18
Source File: util.py    From dockerpty with Apache License 2.0 5 votes vote down vote up
def set_pty_size(fd, size):
    """
    Resize the PTY at `fd` to (rows, cols) size.
    """

    rows, cols = size
    fcntl.ioctl(
        fd,
        termios.TIOCSWINSZ,
        struct.pack('hhhh', rows, cols, 0, 0)
    ) 
Example #19
Source File: test_length_sequence.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_winsize(many_lines, many_columns):
    """Test height and width is appropriately queried in a pty."""
    @as_subprocess
    def child(lines=25, cols=80):
        # set the pty's virtual window size
        val = struct.pack('HHHH', lines, cols, 0, 0)
        fcntl.ioctl(sys.__stdout__.fileno(), termios.TIOCSWINSZ, val)
        t = TestTerminal()
        winsize = t._height_and_width()
        assert t.width == cols
        assert t.height == lines
        assert winsize.ws_col == cols
        assert winsize.ws_row == lines

    child(lines=many_lines, cols=many_columns) 
Example #20
Source File: test_wrap.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_SequenceWrapper(all_terms, many_columns):
    """Test that text wrapping accounts for sequences correctly."""
    @as_subprocess
    def child(kind, lines=25, cols=80):

        # set the pty's virtual window size
        val = struct.pack('HHHH', lines, cols, 0, 0)
        fcntl.ioctl(sys.__stdout__.fileno(), termios.TIOCSWINSZ, val)

        # build a test paragraph, along with a very colorful version
        t = TestTerminal(kind=kind)
        pgraph = u' '.join(
            ('a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefgh',
             'abcdefghi', 'abcdefghij', 'abcdefghijk', 'abcdefghijkl',
             'abcdefghijklm', 'abcdefghijklmn', 'abcdefghijklmno',) * 4)
        pgraph_colored = u''.join([
            t.color(n % 7) + t.bold + ch
            for n, ch in enumerate(pgraph)])

        internal_wrapped = textwrap.wrap(pgraph, t.width,
                                         break_long_words=False)
        my_wrapped = t.wrap(pgraph)
        my_wrapped_colored = t.wrap(pgraph_colored)

        # ensure we textwrap ascii the same as python
        assert (internal_wrapped == my_wrapped)

        # ensure our first and last line wraps at its ends
        first_l = internal_wrapped[0]
        last_l = internal_wrapped[-1]
        my_first_l = my_wrapped_colored[0]
        my_last_l = my_wrapped_colored[-1]
        assert (len(first_l) == t.length(my_first_l))
        assert (len(last_l) == t.length(my_last_l))
        assert (len(internal_wrapped[-1]) == t.length(my_wrapped_colored[-1]))

    child(kind=all_terms, lines=25, cols=many_columns) 
Example #21
Source File: pikspect.py    From pikaur with GNU General Public License v3.0 5 votes vote down vote up
def set_terminal_geometry(file_descriptor: int, rows: int, columns: int) -> None:
    term_geometry_struct = struct.pack("HHHH", rows, columns, 0, 0)
    fcntl.ioctl(
        file_descriptor, termios.TIOCSWINSZ, term_geometry_struct
    ) 
Example #22
Source File: util.py    From mock with GNU General Public License v2.0 5 votes vote down vote up
def resize_pty(pty):
    try:
        winsize = struct.pack('HHHH', 0, 0, 0, 0)
        winsize = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, winsize)
        fcntl.ioctl(pty, termios.TIOCSWINSZ, winsize)
    except IOError:
        # Nice to have, but not necessary
        pass 
Example #23
Source File: shell_logger.py    From thefuck with MIT License 5 votes vote down vote up
def _set_pty_size(master_fd):
    buf = array.array('h', [0, 0, 0, 0])
    fcntl.ioctl(pty.STDOUT_FILENO, termios.TIOCGWINSZ, buf, True)
    fcntl.ioctl(master_fd, termios.TIOCSWINSZ, buf) 
Example #24
Source File: ptyprocess.py    From pipenv-sublime with MIT License 5 votes vote down vote up
def _setwinsize(fd, rows, cols):
    # Some very old platforms have a bug that causes the value for
    # termios.TIOCSWINSZ to be truncated. There was a hack here to work
    # around this, but it caused problems with newer platforms so has been
    # removed. For details see https://github.com/pexpect/pexpect/issues/39
    TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
    # Note, assume ws_xpixel and ws_ypixel are zero.
    s = struct.pack('HHHH', rows, cols, 0, 0)
    fcntl.ioctl(fd, TIOCSWINSZ, s) 
Example #25
Source File: termio.py    From django-gateone with GNU General Public License v3.0 5 votes vote down vote up
def resize(self, rows, cols, em_dimensions=None, ctrl_l=True):
        """
        Resizes the child process's terminal window to *rows* and *cols* by
        first sending it a TIOCSWINSZ event and then sending ctrl-l.

        If *em_dimensions* are provided they will be updated along with the
        rows and cols.

        The sending of ctrl-l can be disabled by setting *ctrl_l* to False.
        """
        logging.debug(
            "Resizing term %s to rows: %s, cols: %s, em_dimensions=%s"
            % (self.term_id, rows, cols, em_dimensions))
        if rows < 2:
            rows = 24
        if cols < 2:
            cols = 80
        self.rows = rows
        self.cols = cols
        self.term.resize(rows, cols, em_dimensions)
        # Sometimes the resize doesn't actually apply (for whatever reason)
        # so to get around this we have to send a different value than the
        # actual value we want then send our actual value.  It's a bug outside
        # of Gate One that I have no idea how to isolate but this has proven to
        # be an effective workaround.
        import fcntl, termios
        s = struct.pack("HHHH", rows, cols, 0, 0)
        try:
            fcntl.ioctl(self.fd, termios.TIOCSWINSZ, s)
        except IOError:
            # Process already ended--no big deal
            return
        try:
            os.kill(self.pid, signal.SIGWINCH) # Send the resize signal
        except OSError:
            return # Process is dead.  Can happen when things go quickly
        if ctrl_l:
            self.write(u'\x0c') # ctrl-l 
Example #26
Source File: environment.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def ioctl(self, fd, cmd, arg):
        """Stub for 'ioctl' syscall
        Return the list of element to pack back depending on target ioctl
        If the ioctl is disallowed, return False
        """
        allowed = False
        disallowed = False
        for test in [(fd, cmd), (None, cmd), (fd, None)]:
            if test in self.ioctl_allowed:
                allowed = True
            if test in self.ioctl_disallowed:
                disallowed = True

        if allowed and disallowed:
            raise ValueError("fd: %x, cmd: %x is allowed and disallowed" % (fd, cmd))

        if allowed:
            if cmd == termios.TCGETS:
                return 0, 0, 0, 0
            elif cmd == termios.TIOCGWINSZ:
                # struct winsize
                # {
                #   unsigned short ws_row;	/* rows, in characters */
                #   unsigned short ws_col;	/* columns, in characters */
                #   unsigned short ws_xpixel;	/* horizontal size, pixels */
                #   unsigned short ws_ypixel;	/* vertical size, pixels */
                # };
                return 1000, 360, 1000, 1000
            elif cmd == termios.TIOCSWINSZ:
                # Ignore it
                return
            else:
                raise RuntimeError("Not implemented")

        elif disallowed:
            return False

        else:
            raise KeyError("Unknown ioctl fd:%x cmd:%x" % (fd, cmd)) 
Example #27
Source File: environment.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        stdin = FileDescriptorSTDIN(0)
        stdout = FileDescriptorSTDOUT(1)
        stderr = FileDescriptorSTDERR(2)
        for std in [stdin, stdout, stderr]:
            std.uid = self.user_uid
            std.gid = self.user_gid
        self.file_descriptors = {
            0: stdin,
            1: stdout,
            2: stderr,
        }
        self.ioctl_allowed = [
            (0, termios.TCGETS),
            (0, termios.TIOCGWINSZ),
            (0, termios.TIOCSWINSZ),
            (1, termios.TCGETS),
            (1, termios.TIOCGWINSZ),
            (1, termios.TIOCSWINSZ),
        ]
        self.ioctl_disallowed = [
            (2, termios.TCGETS),
            (0, termios.TCSETSW),
        ]
        self.filesystem = FileSystem(self.filesystem_base, self)
        self.network = Networking(self) 
Example #28
Source File: test_length_sequence.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def test_winsize(many_lines, many_columns):
    """Test height and width is appropriately queried in a pty."""
    @as_subprocess
    def child(lines=25, cols=80):
        # set the pty's virtual window size
        val = struct.pack('HHHH', lines, cols, 0, 0)
        fcntl.ioctl(sys.__stdout__.fileno(), termios.TIOCSWINSZ, val)
        term = TestTerminal()
        winsize = term._height_and_width()
        assert term.width == cols
        assert term.height == lines
        assert winsize.ws_col == cols
        assert winsize.ws_row == lines

    child(lines=many_lines, cols=many_columns) 
Example #29
Source File: webshell.py    From WebShell with GNU General Public License v2.0 5 votes vote down vote up
def proc_keepalive(self, sid, w, h):
		if not sid in self.session:
			# Start a new session
			self.session[sid] = {
				'state':'unborn',
				'term':	Terminal(w, h),
				'time':	time.time(),
				'w':	w,
				'h':	h}
			return self.proc_spawn(sid)
		elif self.session[sid]['state'] == 'alive':
			self.session[sid]['time'] = time.time()
			# Update terminal size
			if self.session[sid]['w'] != w or self.session[sid]['h'] != h:
				try:
					fcntl.ioctl(fd, 
						struct.unpack('i', 
							struct.pack('I', termios.TIOCSWINSZ)
						)[0],
						struct.pack("HHHH", h, w, 0, 0))
				except (IOError, OSError):
					pass
				self.session[sid]['term'].set_size(w, h)
				self.session[sid]['w'] = w
				self.session[sid]['h'] = h
			return True
		else:
			return False 
Example #30
Source File: ptyprocess.py    From sublime_debugger with MIT License 5 votes vote down vote up
def _setwinsize(fd, rows, cols):
    # Some very old platforms have a bug that causes the value for
    # termios.TIOCSWINSZ to be truncated. There was a hack here to work
    # around this, but it caused problems with newer platforms so has been
    # removed. For details see https://github.com/pexpect/pexpect/issues/39
    TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
    # Note, assume ws_xpixel and ws_ypixel are zero.
    s = struct.pack('HHHH', rows, cols, 0, 0)
    fcntl.ioctl(fd, TIOCSWINSZ, s)