Python termios.TCSANOW Examples

The following are 30 code examples of termios.TCSANOW(). 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: consola_io.py    From simplez-fpga with GNU General Public License v2.0 7 votes vote down vote up
def init():
    if os.name == 'posix':
        global old
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        new[6][termios.VMIN] = 1
        new[6][termios.VTIME] = 0

        # -- Cambiar los atributos
        termios.tcsetattr(fd, termios.TCSANOW, new)

        # -- Restaurar el terminal a la salida
        atexit.register(cleanup_console)
    pass


# -------------------------------------
# Pequena prueba del modulo
# ------------------------------------- 
Example #2
Source File: main.py    From rshell with MIT License 6 votes vote down vote up
def main():
    """This main function saves the stdin termios settings, calls real_main,
       and restores stdin termios settings when it returns.
    """
    save_settings = None
    stdin_fd = -1
    try:
        import termios
        stdin_fd = sys.stdin.fileno()
        save_settings = termios.tcgetattr(stdin_fd)
    except:
        pass
    try:
        real_main()
    finally:
        if save_settings:
            termios.tcsetattr(stdin_fd, termios.TCSANOW, save_settings) 
Example #3
Source File: failover_console.py    From mysql-utilities with GNU General Public License v2.0 6 votes vote down vote up
def getch():
        """Make a get character keyboard method for Posix machines.
        """
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        new[6][termios.VMIN] = 1
        new[6][termios.VTIME] = 0
        termios.tcsetattr(fd, termios.TCSANOW, new)
        key = None
        try:
            key = os.read(fd, 4)
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, old)
        return key 
Example #4
Source File: ptyprocess.py    From sublime_debugger with MIT License 6 votes vote down vote up
def _setecho(fd, state):
    errmsg = 'setecho() may not be called on this platform'

    try:
        attr = termios.tcgetattr(fd)
    except termios.error as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise

    if state:
        attr[3] = attr[3] | termios.ECHO
    else:
        attr[3] = attr[3] & ~termios.ECHO

    try:
        # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
        # blocked on some platforms. TCSADRAIN would probably be ideal.
        termios.tcsetattr(fd, termios.TCSANOW, attr)
    except IOError as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise 
Example #5
Source File: console.py    From mysql-utilities with GNU General Public License v2.0 6 votes vote down vote up
def getch():
        """getch function
        """
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        new[6][termios.VMIN] = 1
        new[6][termios.VTIME] = 0
        termios.tcsetattr(fd, termios.TCSANOW, new)
        key = None
        try:
            key = os.read(fd, 80)
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, old)
        return key 
Example #6
Source File: ptyprocess.py    From pipenv with MIT License 6 votes vote down vote up
def _setecho(fd, state):
    errmsg = 'setecho() may not be called on this platform (it may still be possible to enable/disable echo when spawning the child process)'

    try:
        attr = termios.tcgetattr(fd)
    except termios.error as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise

    if state:
        attr[3] = attr[3] | termios.ECHO
    else:
        attr[3] = attr[3] & ~termios.ECHO

    try:
        # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
        # blocked on some platforms. TCSADRAIN would probably be ideal.
        termios.tcsetattr(fd, termios.TCSANOW, attr)
    except IOError as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise 
Example #7
Source File: kleinanzeigen.py    From ebayKleinanzeigen with Apache License 2.0 6 votes vote down vote up
def wait_key():
    """ Wait for a key press on the console and return it. """
    result = None
    if os.name == 'nt':
        result = input("Press Enter to continue...")
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result 
Example #8
Source File: backup.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
    """Similar to pty.fork, but handle stdin/stdout according to parameters
    instead of connecting to the pty

    :return tuple (subprocess.Popen, pty_master)
    """

    def set_ctty(ctty_fd, master_fd):
        os.setsid()
        os.close(master_fd)
        fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
        if not echo:
            termios_p = termios.tcgetattr(ctty_fd)
            # termios_p.c_lflags
            termios_p[3] &= ~termios.ECHO
            termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
    (pty_master, pty_slave) = os.openpty()
    # pylint: disable=not-an-iterable
    p = yield from asyncio.create_subprocess_exec(*args,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        preexec_fn=lambda: set_ctty(pty_slave, pty_master))
    os.close(pty_slave)
    return p, open(pty_master, 'wb+', buffering=0) 
Example #9
Source File: wizardofoz.py    From saywizard with GNU General Public License v3.0 6 votes vote down vote up
def wait_key():
    ''' Wait for a key press on the console and return it. '''
    result = None
    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getch()
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result 
Example #10
Source File: vt100.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __enter__(self) -> None:
        # NOTE: On os X systems, using pty.setraw() fails. Therefor we are using this:
        try:
            newattr = termios.tcgetattr(self.fileno)
        except termios.error:
            pass
        else:
            newattr[tty.LFLAG] = self._patch_lflag(newattr[tty.LFLAG])
            newattr[tty.IFLAG] = self._patch_iflag(newattr[tty.IFLAG])

            # VMIN defines the number of characters read at a time in
            # non-canonical mode. It seems to default to 1 on Linux, but on
            # Solaris and derived operating systems it defaults to 4. (This is
            # because the VMIN slot is the same as the VEOF slot, which
            # defaults to ASCII EOT = Ctrl-D = 4.)
            newattr[tty.CC][termios.VMIN] = 1  # type: ignore

            termios.tcsetattr(self.fileno, termios.TCSANOW, newattr)

            # Put the terminal in cursor mode. (Instead of application mode.)
            os.write(self.fileno, b"\x1b[?1l") 
Example #11
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_vtime(self, vtime):
        if not isinstance(vtime, (float, int)):
            raise TypeError("Invalid vtime type, should be float or integer.")
        elif not (0 <= vtime <= 25.5):
            raise ValueError("Invalid vtime, can be 0 to 25.5 seconds.")

        try:
            iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror)

        cc[termios.VTIME] = int(float(vtime) * 10.0)

        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror) 
Example #12
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_vmin(self, vmin):
        if not isinstance(vmin, int):
            raise TypeError("Invalid vmin type, should be integer.")
        elif not (0 <= vmin <= 255):
            raise ValueError("Invalid vmin, can be 0 to 255.")

        try:
            iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror)

        cc[termios.VMIN] = vmin

        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror)

        self._use_termios_timeout = vmin > 0 
Example #13
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_xonxoff(self, enabled):
        if not isinstance(enabled, bool):
            raise TypeError("Invalid enabled type, should be boolean.")

        # Get tty attributes
        try:
            (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Getting serial port attributes: " + e.strerror)

        # Modify tty attributes
        iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
        if enabled:
            iflag |= (termios.IXON | termios.IXOFF)

        # Set tty attributes
        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror) 
Example #14
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_databits(self, databits):
        if not isinstance(databits, int):
            raise TypeError("Invalid data bits type, should be integer.")
        elif databits not in [5, 6, 7, 8]:
            raise ValueError("Invalid data bits, can be 5, 6, 7, 8.")

        # Get tty attributes
        try:
            (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Getting serial port attributes: " + e.strerror)

        # Modify tty attributes
        cflag &= ~termios.CSIZE
        cflag |= Serial._DATABITS_TO_CFLAG[databits]

        # Set tty attributes
        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror) 
Example #15
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_baudrate(self, baudrate):
        if not isinstance(baudrate, int):
            raise TypeError("Invalid baud rate type, should be integer.")

        if baudrate not in Serial._BAUDRATE_TO_OSPEED:
            raise ValueError("Unknown baud rate: {:d}".format(baudrate))

        # Get tty attributes
        try:
            (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Getting serial port attributes: " + e.strerror)

        # Modify tty attributes
        cflag &= ~(termios.CBAUD | termios.CBAUDEX)
        cflag |= Serial._BAUDRATE_TO_OSPEED[baudrate]
        ispeed = Serial._BAUDRATE_TO_OSPEED[baudrate]
        ospeed = Serial._BAUDRATE_TO_OSPEED[baudrate]

        # Set tty attributes
        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror) 
Example #16
Source File: __main__.py    From imaginary with MIT License 6 votes vote down vote up
def withSavedTerminalSettings(fd, blockingCall):
    """
    Save and restore terminal settings for the given file descriptor.

    @param fd: The file descriptor, a PTY, to preserve terminal settings for.
    @type fd: L{int}

    @param blockingCall: A 0-argument callable that might modify C{fd}'s
        terminal settings.
    @type blockingCall: L{callable}

    @return: The result of L{blockingCall}.
    """
    oldSettings = termios.tcgetattr(fd)
    tty.setraw(fd)
    try:
        return blockingCall()
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
        os.write(fd, CLEAR_SCREEN) 
Example #17
Source File: ptyprocess.py    From pipenv-sublime with MIT License 6 votes vote down vote up
def _setecho(fd, state):
    errmsg = 'setecho() may not be called on this platform'

    try:
        attr = termios.tcgetattr(fd)
    except termios.error as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise

    if state:
        attr[3] = attr[3] | termios.ECHO
    else:
        attr[3] = attr[3] & ~termios.ECHO

    try:
        # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
        # blocked on some platforms. TCSADRAIN would probably be ideal.
        termios.tcsetattr(fd, termios.TCSANOW, attr)
    except IOError as err:
        if err.args[0] == errno.EINVAL:
            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
        raise 
Example #18
Source File: serial.py    From python-periphery with MIT License 6 votes vote down vote up
def _set_stopbits(self, stopbits):
        if not isinstance(stopbits, int):
            raise TypeError("Invalid stop bits type, should be integer.")
        elif stopbits not in [1, 2]:
            raise ValueError("Invalid stop bits, can be 1, 2.")

        # Get tty attributes
        try:
            (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Getting serial port attributes: " + e.strerror)

        # Modify tty attributes
        cflag &= ~termios.CSTOPB
        if stopbits == 2:
            cflag |= termios.CSTOPB

        # Set tty attributes
        try:
            termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
        except termios.error as e:
            raise SerialError(e.errno, "Setting serial port attributes: " + e.strerror) 
Example #19
Source File: stack_symbolizer.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def __init__(self, args, close_stderr=False):
    pid, fd = pty.fork()
    if pid == 0:
      # We're the child. Transfer control to command.
      if close_stderr:
        dev_null = os.open('/dev/null', 0)
        os.dup2(dev_null, 2)
      os.execvp(args[0], args)
    else:
      # Disable echoing.
      attr = termios.tcgetattr(fd)
      attr[3] = attr[3] & ~termios.ECHO
      termios.tcsetattr(fd, termios.TCSANOW, attr)
      # Set up a file()-like interface to the child process
      self.r = os.fdopen(fd, 'r', 1)
      self.w = os.fdopen(os.dup(fd), 'w', 1) 
Example #20
Source File: keyboard_recorder.py    From mozc-devices with Apache License 2.0 6 votes vote down vote up
def _set_raw_mode_stdin():
  fno = sys.stdin.fileno()
  attr_old = termios.tcgetattr(fno)
  fcntl_old = fcntl.fcntl(fno, fcntl.F_GETFL)

  attr_new = termios.tcgetattr(fno)
  attr_new[3] = attr_new[3] & ~termios.ECHO & ~termios.ICANON
  termios.tcsetattr(fno, termios.TCSADRAIN, attr_new)

  fcntl.fcntl(fno, fcntl.F_SETFL, fcntl_old | os.O_NONBLOCK)

  def reset_raw_mode():
    termios.tcsetattr(fno, termios.TCSANOW, attr_old)
    fcntl.fcntl(fno, fcntl.F_SETFL, fcntl_old)

  return reset_raw_mode 
Example #21
Source File: pikspect.py    From pikaur with GNU General Public License v3.0 5 votes vote down vote up
def _restore(cls, what: Optional[TcAttrsType] = None) -> None:
        if sys.stdout.isatty():
            # termios.tcdrain(sys.stdout.fileno())
            # if sys.stderr.isatty():
            #     termios.tcdrain(sys.stderr.fileno())
            # if sys.stdin.isatty():
            #     termios.tcflush(sys.stdin.fileno(), termios.TCIOFLUSH)
            if what:
                termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, what) 
Example #22
Source File: terminalkeyboard.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def read_key():
    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)

    oldstdinfl = fcntl.fcntl(1, fcntl.F_GETFL)
    try:
        seq = ''
        while characters_left_for_sequence(seq):
            if len(seq) > 0:
                fcntl.fcntl(1, fcntl.F_SETFL, oldstdinfl | os.O_NONBLOCK)
            ch = sys.stdin.read(1)
            if not ch:
                break
            seq += ch
    except IOError:
        pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(1, fcntl.F_SETFL, oldstdinfl)

    try:
        result = TerminalKeyDict[seq]
    except KeyError:
        result = seq

    return result 
Example #23
Source File: util.py    From pre-commit with MIT License 5 votes vote down vote up
def __enter__(self) -> 'Pty':
            self.r, self.w = openpty()

            # tty flags normally change \n to \r\n
            attrs = termios.tcgetattr(self.r)
            assert isinstance(attrs[1], int)
            attrs[1] &= ~(termios.ONLCR | termios.OPOST)
            termios.tcsetattr(self.r, termios.TCSANOW, attrs)

            return self 
Example #24
Source File: __init__.py    From hase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_pty() -> Tuple[IO[Any], str]:
    master_fd, slave_fd = pty.openpty()
    # disable echoing
    tty.setraw(master_fd, termios.TCSANOW)
    tty.setraw(slave_fd, termios.TCSANOW)
    ptsname = os.ttyname(slave_fd)
    os.close(slave_fd)
    # make i/o unbuffered
    return os.fdopen(master_fd, "wb+", 0), ptsname 
Example #25
Source File: serialposix.py    From android3dblendermouse with Apache License 2.0 5 votes vote down vote up
def _reconfigure_port(self, force_update=True):
        """Set communication parameters on opened port."""
        super(VTIMESerial, self)._reconfigure_port()
        fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK

        if self._inter_byte_timeout is not None:
            vmin = 1
            vtime = int(self._inter_byte_timeout * 10)
        else:
            vmin = 0
            vtime = int(self._timeout * 10)
        try:
            orig_attr = termios.tcgetattr(self.fd)
            iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
        except termios.error as msg:      # if a port is nonexistent but has a /dev file, it'll fail here
            raise serial.SerialException("Could not configure port: %s" % msg)

        if vtime < 0 or vtime > 255:
            raise ValueError('Invalid vtime: %r' % vtime)
        cc[termios.VTIME] = vtime
        cc[termios.VMIN] = vmin

        termios.tcsetattr(
                self.fd,
                termios.TCSANOW,
                [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) 
Example #26
Source File: miniterm.py    From android3dblendermouse with Apache License 2.0 5 votes vote down vote up
def setup(self):
            new = termios.tcgetattr(self.fd)
            new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
            new[6][termios.VMIN] = 1
            new[6][termios.VTIME] = 0
            termios.tcsetattr(self.fd, termios.TCSANOW, new) 
Example #27
Source File: terminal_input.py    From goreviewpartner with GNU General Public License v3.0 5 votes vote down vote up
def stop_was_requested(self):
        """Check whether a 'keyboard stop' instruction has been sent.

        Returns true if ^X has been sent on the controlling terminal.

        Consumes all available input on /dev/tty.

        """
        if not self.enabled:
            return False
        # Don't try to read the terminal if we're in the background.
        # There's a race here, if we're backgrounded just after this check, but
        # I don't see a clean way to avoid it.
        if os.tcgetpgrp(self.tty.fileno()) != os.getpid():
            return False
        try:
            termios.tcsetattr(self.tty, termios.TCSANOW, self.cbreak_tcattr)
        except EnvironmentError:
            return False
        try:
            seen_ctrl_x = False
            while True:
                c = os.read(self.tty.fileno(), 1)
                if not c:
                    break
                if c == "\x18":
                    seen_ctrl_x = True
        except EnvironmentError:
            seen_ctrl_x = False
        finally:
            termios.tcsetattr(self.tty, termios.TCSANOW, self.clean_tcattr)
        return seen_ctrl_x 
Example #28
Source File: autoreload.py    From python with Apache License 2.0 5 votes vote down vote up
def ensure_echo_on():
    if termios:
        fd = sys.stdin
        if fd.isatty():
            attr_list = termios.tcgetattr(fd)
            if not attr_list[3] & termios.ECHO:
                attr_list[3] |= termios.ECHO
                if hasattr(signal, 'SIGTTOU'):
                    old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
                else:
                    old_handler = None
                termios.tcsetattr(fd, termios.TCSANOW, attr_list)
                if old_handler is not None:
                    signal.signal(signal.SIGTTOU, old_handler) 
Example #29
Source File: terminal.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def stopService(self):
        """
        Stop the service.
        """
        # Restore terminal settings
        termios.tcsetattr(self.terminalFD, termios.TCSANOW, self._oldTerminalSettings)
        os.write(self.terminalFD, "\r\x1bc\r") 
Example #30
Source File: _system_commands.py    From colabtools with Apache License 2.0 5 votes vote down vote up
def _configure_term_settings(pty_fd):
  term_settings = termios.tcgetattr(pty_fd)
  # ONLCR transforms NL to CR-NL, which is undesirable. Ensure this is disabled.
  # http://man7.org/linux/man-pages/man3/termios.3.html
  term_settings[1] &= ~termios.ONLCR

  # ECHOCTL echoes control characters, which is undesirable.
  term_settings[3] &= ~termios.ECHOCTL

  termios.tcsetattr(pty_fd, termios.TCSANOW, term_settings)