我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用termios.TCSANOW。
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
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
def keyboard(callback, exit='q'): 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) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while True: try: ch = sys.stdin.read(1) if ch: callback(ch) if ch == exit: break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
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)
def __enter__(self): # 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 termios.tcsetattr(self.fileno, termios.TCSANOW, newattr) # Put the terminal in cursor mode. (Instead of application mode.) os.write(self.fileno, b'\x1b[?1l')
def reconfigure(self, state=True): """ Allow HUPCL (hang up on close) VMIN, VTIME = 0 """ fd = self.fileno() orig_attr = termios.tcgetattr(fd) iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr cflag |= termios.HUPCL cc[termios.VMIN] = 0 cc[termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
def get_keypress(): """Wait for a keypress and return key pressed. This is the *nix version of this command""" import termios, fcntl, sys, os 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) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while 1: try: c = sys.stdin.read(1) break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c
def getch(): fd = sys.stdin.fileno() oldattr = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while True: try: c = sys.stdin.read(1) except IOError: pass else: return c finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldattr) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
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): '''Set controlling terminal''' 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() p = subprocess.Popen(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)
def setup(self): self.old = termios.tcgetattr(self.fd) 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)
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)
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(0, "\r\x1bc\r")
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])
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)
def set(self, when=termios.TCSANOW): termios.tcsetattr(self.fd, when, self.as_list())
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])
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
def __exit__(self, *a, **kw): if self.attrs_before is not None: try: termios.tcsetattr(self.fileno, termios.TCSANOW, self.attrs_before) except termios.error: pass # # Put the terminal in application mode. # self._stdout.write('\x1b[?1h')
def setecho (self, state): """This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.expect (['1234']) p.expect (['1234']) p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['abcd']) p.expect (['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['1234']) p.expect (['1234']) p.expect (['abcd']) p.expect (['wxyz']) """ self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = attr[3] | termios.ECHO else: attr[3] = attr[3] & ~termios.ECHO # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
def run(self): if os.name != "posix": raise ValueError("Can only be run on Posix systems") return buffer = "" # While PySerial would be preferable and more machine-independant, # it does not support echo suppression with open(self.dbgser_tty_name, 'r+') as dbgser: # Config the debug serial port oldattrs = termios.tcgetattr(dbgser) newattrs = termios.tcgetattr(dbgser) newattrs[4] = termios.B115200 # ispeed newattrs[5] = termios.B115200 # ospeed newattrs[3] = newattrs[3] & ~termios.ICANON & ~termios.ECHO newattrs[6][termios.VMIN] = 0 newattrs[6][termios.VTIME] = 10 termios.tcsetattr(dbgser, termios.TCSANOW, newattrs) # As long as we weren't asked to stop, try to capture dbgserial # output and push each line up the result queue. try: while not self.stoprequest.isSet(): ch = dbgser.read(1) if ch: if ch == "\n": # Push the line (sans newline) into our queue # and clear the buffer for the next line. self.result_q.put(buffer) buffer = "" elif ch != "\r": buffer += ch except IOError: pass finally: # Restore previous settings termios.tcsetattr(dbgser, termios.TCSAFLUSH, oldattrs) # Flush any partial buffer if buffer: self.result_q.put(buffer)
def prepare_tty(): "set the terminal in char mode (return each keyboard press at once) and"\ " switch off echoing of this input; return the original settings" stdin_fd = sys.stdin.fileno() # will most likely be 0 ;-> old_stdin_config = termios.tcgetattr(stdin_fd) [ iflag, oflag, cflag, lflag, ispeed, ospeed, cc ] = \ termios.tcgetattr(stdin_fd) cc[termios.VTIME] = 1 cc[termios.VMIN] = 1 iflag = iflag & ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP | termios.INLCR | termios.IGNCR | #termios.ICRNL | termios.IXON) # oflag = oflag & ~termios.OPOST cflag = cflag | termios.CS8 lflag = lflag & ~(termios.ECHO | termios.ECHONL | termios.ICANON | # termios.ISIG | termios.IEXTEN) termios.tcsetattr(stdin_fd, termios.TCSANOW, [ iflag, oflag, cflag, lflag, ispeed, ospeed, cc ]) return (stdin_fd, old_stdin_config)
def getch(): ''' Get character. ''' # get character try: termios.tcsetattr(fd,termios.TCSANOW,new_settings) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # return return ch # ----------------------------------------------------------------------------------
def _ensure_echo_on(): # pragma: no cover if not sys.stdin.isatty(): return None file_descriptor_attrs = termios.tcgetattr(sys.stdin) _, _, _, lflag, _, _, _ = file_descriptor_attrs if not lflag & termios.ECHO: lflag |= termios.ECHO try: old_sig_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) except AttributeError: old_sig_handler = None termios.tcsetattr(sys.stdin, termios.TCSANOW, file_descriptor_attrs) if old_sig_handler is not None: signal.signal(signal.SIGTTOU, old_sig_handler)
def _open_pty(self): """Create a PTY """ # get our terminal params self.tcattr = termios.tcgetattr(STDIN) winsize = fcntl.ioctl(STDIN, termios.TIOCGWINSZ, '0123') # open a pty self.master, self.slave = os.openpty() # set the slave's terminal params termios.tcsetattr(self.slave, termios.TCSANOW, self.tcattr) fcntl.ioctl(self.slave, termios.TIOCSWINSZ, winsize)
def _fix_tty(self): """Set suitable tty options """ assert self.tcattr is not None iflag, oflag, cflag, lflag, ispeed, ospeed, chars = self.tcattr # pylint:disable=unpacking-non-sequence # equivalent to cfmakeraw iflag &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP | termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IXON) oflag &= ~termios.OPOST lflag &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.ISIG | termios.IEXTEN) cflag &= ~(termios.CSIZE | termios.PARENB) cflag |= termios.CS8 termios.tcsetattr(STDIN, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, chars])