Python termios.tcsetattr() Examples
The following are 30
code examples of termios.tcsetattr().
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 |
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: _termui_impl.py From pipenv with MIT License | 6 votes |
def raw_terminal(): if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) yield fd finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass
Example #3
Source File: _termui_impl.py From pcocc with GNU General Public License v3.0 | 6 votes |
def getchar(echo): if not isatty(sys.stdin): f = open('/dev/tty') fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = os.read(fd, 32) if echo and isatty(sys.stdout): sys.stdout.write(ch) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass _translate_ch_to_exc(ch) return ch.decode(get_best_encoding(sys.stdin), 'replace')
Example #4
Source File: backup.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
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 #5
Source File: runscans.py From ivre with GNU General Public License v3.0 | 6 votes |
def restore_echo(): """Hack for https://stackoverflow.com/questions/6488275 equivalent issue with Nmap (from http://stackoverflow.com/a/8758047/3223422) """ try: fdesc = sys.stdin.fileno() except ValueError: return try: attrs = termios.tcgetattr(fdesc) except termios.error: return attrs[3] = attrs[3] | termios.ECHO termios.tcsetattr(fdesc, termios.TCSADRAIN, attrs)
Example #6
Source File: readchar.py From marker with MIT License | 6 votes |
def read_char_no_blocking(): ''' Read a character in nonblocking mode, if no characters are present in the buffer, return an empty string ''' fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) old_flags = fcntl.fcntl(fd, fcntl.F_GETFL) try: tty.setraw(fd, termios.TCSADRAIN) fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK) return sys.stdin.read(1) except IOError as e: ErrorNumber = e[0] # IOError with ErrorNumber 11(35 in Mac) is thrown when there is nothing to read(Resource temporarily unavailable) if (sys.platform.startswith("linux") and ErrorNumber != 11) or (sys.platform == "darwin" and ErrorNumber != 35): raise return "" finally: fcntl.fcntl(fd, fcntl.F_SETFL, old_flags) termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Example #7
Source File: tty.py From bob with GNU General Public License v3.0 | 6 votes |
def __init__(self, verbosity, maxJobs): super().__init__(verbosity) self.__index = 1 self.__maxJobs = maxJobs self.__jobs = {} self.__slots = [None] * maxJobs self.__tasksDone = 0 self.__tasksNum = 1 # disable cursor print("\x1b[?25l") # disable echo try: import termios fd = sys.stdin.fileno() self.__oldTcAttr = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ECHO termios.tcsetattr(fd, termios.TCSADRAIN, new) except ImportError: pass
Example #8
Source File: _termui_impl.py From jbox with MIT License | 6 votes |
def getchar(echo): if not isatty(sys.stdin): f = open('/dev/tty') fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = os.read(fd, 32) if echo and isatty(sys.stdout): sys.stdout.write(ch) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass _translate_ch_to_exc(ch) return ch.decode(get_best_encoding(sys.stdin), 'replace')
Example #9
Source File: ptyprocess.py From pipenv with MIT License | 6 votes |
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 #10
Source File: stack_symbolizer.py From clusterfuzz with Apache License 2.0 | 6 votes |
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 #11
Source File: serial.py From python-periphery with MIT License | 6 votes |
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 |
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: _termui_impl.py From RSSNewsGAE with Apache License 2.0 | 6 votes |
def getchar(echo): if not isatty(sys.stdin): f = open('/dev/tty') fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = os.read(fd, 32) if echo and isatty(sys.stdout): sys.stdout.write(ch) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass _translate_ch_to_exc(ch) return ch.decode(get_best_encoding(sys.stdin), 'replace')
Example #14
Source File: _termui_impl.py From recruit with Apache License 2.0 | 6 votes |
def raw_terminal(): if not isatty(sys.stdin): f = open('/dev/tty') fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) yield fd finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass
Example #15
Source File: getch.py From flyingros with GNU General Public License v3.0 | 6 votes |
def __call__(self): import sys, tty, termios from select import select fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) # [ Wait until ready for reading, # wait until ready for writing # wait for an "exception condition" ] # The below line times out after 1 second # This can be changed to a floating-point value if necessary [i, o, e] = select([sys.stdin.fileno()], [], [], 1) if i: ch = sys.stdin.read(1) else: ch = None finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
Example #16
Source File: serial.py From python-periphery with MIT License | 6 votes |
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 #17
Source File: serial.py From python-periphery with MIT License | 6 votes |
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 #18
Source File: serial.py From python-periphery with MIT License | 6 votes |
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: serial.py From python-periphery with MIT License | 6 votes |
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 #20
Source File: utils.py From multi-v2ray with GNU General Public License v3.0 | 5 votes |
def readchar(prompt=""): if prompt: sys.stdout.write(prompt) sys.stdout.flush() fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) print(ch) return ch.strip()
Example #21
Source File: utilities.py From aurman with MIT License | 5 votes |
def ask_user(question: str, default: bool, new_line: bool = False) -> bool: """ Asks the user a yes/no question. :param question: The question to ask :param default: The default answer, if user presses enter. True for yes, False for no :param new_line: If new_line before printing the question :return: yes: True, no: False """ yes = ["y"] no = ["n"] if default: yes.append("") choices = "Y/n" else: no.append("") choices = "N/y" while True: print(aurman_question("{} {}: ".format(question, choices), new_line=new_line, to_print=False), end='', flush=True) # see https://stackoverflow.com/a/36974338 fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setcbreak(fd) answer = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) print(flush=True) user_choice = answer.strip().lower() if user_choice in yes or user_choice in no: return user_choice in yes aurman_error("That was not a valid choice!")
Example #22
Source File: helpers.py From decrypt-ios-apps-script with MIT License | 5 votes |
def interactive_shell(chan, callback=None): oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = u(chan.recv(1024)) if len(x) == 0: sys.stdout.write("\r\n[+] Terminating SSH connection\r\n") sys.stdout.flush() if callback != None: callback() break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break chan.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #23
Source File: control_thread.py From flyingros with GNU General Public License v3.0 | 5 votes |
def __call__(self): import sys, tty, termios from select import select fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) [i, o, e] = select([sys.stdin.fileno()], [], [], 1) if i: ch = sys.stdin.read(1) else: ch = None finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
Example #24
Source File: terminal.py From deepWordBug with Apache License 2.0 | 5 votes |
def raw(self): r""" A context manager for :func:`tty.setraw`. Although both :meth:`break` and :meth:`raw` modes allow each keystroke to be read immediately after it is pressed, Raw mode disables processing of input and output. In cbreak mode, special input characters such as ``^C`` or ``^S`` are interpreted by the terminal driver and excluded from the stdin stream. In raw mode these values are receive by the :meth:`inkey` method. Because output processing is not done, the newline ``'\n'`` is not enough, you must also print carriage return to ensure that the cursor is returned to the first column:: with term.raw(): print("printing in raw mode", end="\r\n") """ if HAS_TTY and self._keyboard_fd is not None: # Save current terminal mode: save_mode = termios.tcgetattr(self._keyboard_fd) save_line_buffered = self._line_buffered tty.setraw(self._keyboard_fd, termios.TCSANOW) try: self._line_buffered = False yield finally: # Restore prior mode: termios.tcsetattr(self._keyboard_fd, termios.TCSAFLUSH, save_mode) self._line_buffered = save_line_buffered else: yield
Example #25
Source File: serial.py From python-periphery with MIT License | 5 votes |
def _set_parity(self, parity): if not isinstance(parity, str): raise TypeError("Invalid parity type, should be string.") elif parity.lower() not in ["none", "even", "odd"]: raise ValueError("Invalid parity, can be: \"none\", \"even\", \"odd\".") parity = parity.lower() # 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.INPCK | termios.ISTRIP) cflag &= ~(termios.PARENB | termios.PARODD) if parity != "none": iflag |= (termios.INPCK | termios.ISTRIP) cflag |= termios.PARENB if parity == "odd": cflag |= termios.PARODD # 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 #26
Source File: process_utils.py From airflow with Apache License 2.0 | 5 votes |
def execute_interactive(cmd: List[str], **kwargs): """ Runs the new command as a subprocess and ensures that the terminal's state is restored to its original state after the process is completed e.g. if the subprocess hides the cursor, it will be restored after the process is completed. """ log.info("Executing cmd: %s", " ".join([shlex.quote(c) for c in cmd])) old_tty = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) # open pseudo-terminal to interact with subprocess master_fd, slave_fd = pty.openpty() try: # pylint: disable=too-many-nested-blocks # use os.setsid() make it run in a new process group, or bash job control will not be enabled proc = subprocess.Popen( cmd, stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, universal_newlines=True, **kwargs ) while proc.poll() is None: readable_fbs, _, _ = select.select([sys.stdin, master_fd], [], []) if sys.stdin in readable_fbs: input_data = os.read(sys.stdin.fileno(), 10240) os.write(master_fd, input_data) if master_fd in readable_fbs: output_data = os.read(master_fd, 10240) if output_data: os.write(sys.stdout.fileno(), output_data) finally: # restore tty settings back termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
Example #27
Source File: firm_module.py From odoo-development with GNU Affero General Public License v3.0 | 5 votes |
def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
Example #28
Source File: serialposix.py From ddt4all with GNU General Public License v3.0 | 5 votes |
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) elif self._timeout is None: vmin = 1 vtime = 0 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: {}".format(msg)) if vtime < 0 or vtime > 255: raise ValueError('Invalid vtime: {!r}'.format(vtime)) cc[termios.VTIME] = vtime cc[termios.VMIN] = vmin termios.tcsetattr( self.fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
Example #29
Source File: getch.py From odoo-development with GNU Affero General Public License v3.0 | 5 votes |
def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
Example #30
Source File: stdio.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def runWithProtocol(klass): fd = sys.__stdin__.fileno() oldSettings = termios.tcgetattr(fd) tty.setraw(fd) try: p = ServerProtocol(klass) stdio.StandardIO(p) reactor.run() finally: termios.tcsetattr(fd, termios.TCSANOW, oldSettings) os.write(fd, b"\r\x1bc\r")