def __init__(self, echo=False) : '''Put the terminal into cbreak and noecho mode.''' self.fd = sys.stdin.fileno() self.oldterm = termios.tcgetattr(self.fd) newattr = termios.tcgetattr(self.fd) newattr[3] = newattr[3] & ~termios.ICANON if not echo : newattr[3] = newattr[3] & ~termios.ECHO termios.tcsetattr(self.fd, termios.TCSANOW, newattr) self.oldflags = fcntl.fcntl(self.fd, fcntl.F_GETFL) fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK) # Sad hack: when the destructor __del__ is called, # the fcntl module may already be unloaded, so we can no longer # call fcntl.fcntl() to set the terminal back to normal. # So just in case, store a reference to the fcntl module, # and also to termios (though I haven't yet seen a case # where termios was gone -- for some reason it's just fnctl). # The idea of keeping references to the modules comes from # http://bugs.python.org/issue5099 # though I don't know if it'll solve the problem completely. self.fcntl = fcntl self.termios = termios
def __enter__(self): self.old_cfg = None # Ignore all this if the input stream is not a tty. if not self.stream.isatty(): return try: # import and mark whether it worked. import termios # save old termios settings fd = self.stream.fileno() self.old_cfg = termios.tcgetattr(fd) # create new settings with canonical input and echo # disabled, so keypresses are immediate & don't echo. self.new_cfg = termios.tcgetattr(fd) self.new_cfg[3] &= ~termios.ICANON self.new_cfg[3] &= ~termios.ECHO # Apply new settings for terminal termios.tcsetattr(fd, termios.TCSADRAIN, self.new_cfg) except Exception, e: pass # Some OS's do not support termios, so ignore.
def enable_rawmode(self, fd): """Enable raw mode""" if not os.isatty(fd): return -1 # ensure cleanup upon exit/disaster if not self.atexit_flag: atexit.register(self.atexit) self.atexit_flag = True # modify the original mode self.orig_termios = termios.tcgetattr(fd) raw = termios.tcgetattr(fd) # input modes: no break, no CR to NL, no parity check, no strip char, no start/stop output control raw[_C_IFLAG] &= ~(termios.BRKINT | termios.ICRNL | termios.INPCK | termios.ISTRIP | termios.IXON) # output modes - disable post processing raw[_C_OFLAG] &= ~(termios.OPOST) # control modes - set 8 bit chars raw[_C_CFLAG] |= (termios.CS8) # local modes - echo off, canonical off, no extended functions, no signal chars (^Z,^C) raw[_C_LFLAG] &= ~(termios.ECHO | termios.ICANON | termios.IEXTEN | termios.ISIG) # control chars - set return condition: min number of bytes and timer. # We want read to return every single byte, without timeout. raw[_C_CC][termios.VMIN] = 1 raw[_C_CC][termios.VTIME] = 0 # put terminal in raw mode after flushing termios.tcsetattr(fd, termios.TCSAFLUSH, raw) self.rawmode = True return 0
def __enter__(self): # prepare standard file descriptors for raw manipulation self.was_blocking = os.get_blocking(0) os.set_blocking(0, False) try: self.terminal_attr_stdin = termios.tcgetattr(0) self.terminal_attr_stdout = termios.tcgetattr(1) self.terminal_attr_stderr = termios.tcgetattr(2) tty.setraw(0) tty.setraw(1) tty.setraw(2) except termios.error: # probably redirected self.terminal_attr_stdin = None # redirect standard file descriptors to new PTY master, slave = pty.openpty() os.set_blocking(master, False) self.real_stdin = os.dup(0) self.real_stdout = os.dup(1) self.real_stderr = os.dup(2) os.close(0) os.close(1) os.close(2) os.dup2(slave, 0) os.dup2(slave, 1) os.dup2(slave, 2) os.close(slave) self.terminal_pipe = master # start REPL in separate thread threading.Thread(target=repl, args=(self,), daemon=True).start() return self
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 _wait_for_keypress(): """ Wait for a key press on the console and return it. Borrowed from http://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key """ result = None if os.name == "nt": # noinspection PyUnresolvedReferences 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 getch(): "Returns a single character" if getch.platform is None: try: # Window's python? import msvcrt getch.platform = 'windows' except ImportError: # Fallback... try: import tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) getch.platform = 'unix' except termios.error: getch.platform = 'dumb' if getch.platform == 'windows': import msvcrt return msvcrt.getch() elif getch.platform == 'unix': import 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 else: return sys.stdin.read(1).strip().lower()
def main(): fd = sys.stdin.fileno() # 0, of course. oldterm = termios.tcgetattr(fd) newterm = termios.tcgetattr(fd) newterm[3] = newterm[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newterm) drone = ARDrone() init(drone) try: while True: char = sys.stdin.read(1).lower() print("Got character", '\\n' if char == '\n' else char) eval(char + '()') except: traceback.print_exc() print('landing...') l() drone.halt() termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
def _make_eof_intr(): """Set constants _EOF and _INTR. This avoids doing potentially costly operations on module load. """ global _EOF, _INTR if (_EOF is not None) and (_INTR is not None): return # inherit EOF and INTR definitions from controlling process. try: from termios import VEOF, VINTR try: fd = sys.__stdin__.fileno() except ValueError: # ValueError: I/O operation on closed file fd = sys.__stdout__.fileno() intr = ord(termios.tcgetattr(fd)[6][VINTR]) eof = ord(termios.tcgetattr(fd)[6][VEOF]) except (ImportError, OSError, IOError, ValueError, termios.error): # unless the controlling process is also not a terminal, # such as cron(1), or when stdin and stdout are both closed. # Fall-back to using CEOF and CINTR. There try: from termios import CEOF, CINTR (intr, eof) = (CINTR, CEOF) except ImportError: # ^C, ^D (intr, eof) = (3, 4) _INTR = _byte(intr) _EOF = _byte(eof)
def getchar(): ''' Equivale al comando getchar() di C ''' fd = sys.stdin.fileno() if os.isatty(fd): 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 try: termios.tcsetattr(fd, termios.TCSANOW, new) termios.tcsendbreak(fd,0) ch = os.read(fd,7) finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) else: ch = os.read(fd,7) return(ch)
def run(self): 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 not self.stopped(): try: c = sys.stdin.read(16) for fn in self.registered_fns[c]: fn() # print "Called registered func %s for %s" % (fn,repr(c)) #print 'Got char %s' % c if c == 'q': self.stop() except IOError: pass #time.sleep(.1) finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) print 'Keyboard handler stopped.'
def echo_off(self): self.oldterm = termios.tcgetattr(self.fd) self.newattr = termios.tcgetattr(self.fd) self.newattr[3] = self.newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr) self.oldflags = fcntl.fcntl(self.fd, fcntl.F_GETFL) fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)
def input_loop(url_prefix): global plex_keys while True: 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(3) break except IOError: time.sleep(0.1) pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) if c == 'q': clear() exit(0) elif c == '*': print "\n" change_defaults_i() del sys.argv[1:] main() elif c in plex_keys: urllib2.urlopen(url_prefix + plex_keys[c]).read()
def getchar(prompt, hidden=False, end='\n', timeout=None): '''读取一个字符''' import termios sys.stdout.write(prompt) sys.stdout.flush() fd = sys.stdin.fileno() def _read(): if timeout is None: ch = sys.stdin.read(1) else: ch = _timed_read(sys.stdin, timeout) return ch if os.isatty(fd): old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) if hidden: new[3] = new[3] & ~termios.ICANON & ~termios.ECHO else: new[3] = new[3] & ~termios.ICANON new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 try: termios.tcsetattr(fd, termios.TCSANOW, new) termios.tcsendbreak(fd, 0) ch = _read() finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) else: ch = _read() sys.stdout.write(end) return ch
def warning(message, answer=None): """ Print warning message into srdErr and may can for answer :param message: message :param answer: list of supported options. Default is first item. """ c = "" sys.stderr.write("\n\x1b[92;01m%s " % message) if answer: 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) c = (u"%s" % c).lower() sys.stderr.write(" %s\x1b[39;49;00m\n\n" % c) if answer: for it in answer: if c in it: return c return answer.pop(0)
def run(self): import termios import fcntl import sys import 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 not self.stop_event.is_set(): try: c = sys.stdin.read(1) for b in self.buffers: b.append(c) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def getch(): ''' Get a character from stdin ''' 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: c = sys.stdin.read(1) if c != "": break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c
def get_input(self): 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) msg = '' try: while True: try: c = sys.stdin.read(1) # print "Got character", repr(c) msg = msg + c self.draw_text(msg) # if c == '\n': # msg = msg + os.system(msg) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def getkey(): """Capture a single key press. Capture a key press event, and return the appropriate data in a tuple (c,(x,x,x,x)), where c denotes the character value of the key pressed, while the (x,x,x,x) tuple contains the numeric value of the 4 original bytes. This can be useful if the key pressed has no visible form. Examples: Pressing <c> results in ('c',(99,0,0,0)) Pressing <enter> results in ('\n',(10,0,0,0)) Pressing <up> results in ('', (27,91,65,0)) Pressing <F12> results in ('', (27, 91, 50, 52))""" 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) c = None try: c = os.read(fd, 4) finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) return ( c, (ord(c[0]), ord(c[1]) if len(c) > 1 else 0, ord(c[2]) if len(c) > 2 else 0, ord(c[3]) if len(c) > 3 else 0), )
def __init__(self, slave=0, pid=os.getpid()): # apparently python GC's modules before class instances so, here # we have some hax to ensure we can restore the terminal state. self.termios, self.fcntl = termios, fcntl # open our controlling PTY self.pty = open(os.readlink("/proc/%d/fd/%d" % (pid, slave)), "rb+") # store our old termios settings so we can restore after # we are finished self.oldtermios = termios.tcgetattr(self.pty) # get the current settings se we can modify them newattr = termios.tcgetattr(self.pty) # set the terminal to uncanonical mode and turn off # input echo. newattr[3] &= ~termios.ICANON & ~termios.ECHO # don't handle ^C / ^Z / ^\ newattr[6][termios.VINTR] = '\x00' newattr[6][termios.VQUIT] = '\x00' newattr[6][termios.VSUSP] = '\x00' # set our new attributes termios.tcsetattr(self.pty, termios.TCSADRAIN, newattr) # store the old fcntl flags self.oldflags = fcntl.fcntl(self.pty, fcntl.F_GETFL) # fcntl.fcntl(self.pty, fcntl.F_SETFD, fcntl.FD_CLOEXEC) # make the PTY non-blocking fcntl.fcntl(self.pty, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)
def getchar(prompt, hidden=False, end='\n'): '''读取一个字符''' import termios sys.stdout.write(prompt) sys.stdout.flush() fd = sys.stdin.fileno() if os.isatty(fd): old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) if hidden: new[3] = new[3] & ~termios.ICANON & ~termios.ECHO else: new[3] = new[3] & ~termios.ICANON new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 try: termios.tcsetattr(fd, termios.TCSANOW, new) termios.tcsendbreak(fd, 0) ch = os.read(fd, 7) finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) else: ch = os.read(fd, 7) sys.stdout.write(end) return(ch.decode())
def get_user_command(): ''' Gets the command character from stdin, if any. @note This code is from/based on: http://docs.python.org/faq/library#how-do-i-get-a-single-keypress-at-a-time @return Character inputted by user. None if there isn't any. ''' 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: try: c = sys.stdin.read(1) if c != '': return c else: return None except IOError: return None finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def wait_key(message = ''): ''' Wait for a key press on the console and return it. ''' if message != '': print (message) 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 __call__(self): import sys, termios, fcntl, os fd = sys.stdin.fileno() oldattr = termios.tcgetattr(fd) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) c = 0 try: newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) while True: try: c = sys.stdin.read(1) break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldattr) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c
def oldstat(pid, events, t, ann=None, norm=False, guest=False): evcmd = ",".join(events) if guest: cmd = "sudo perf kvm stat" else: cmd = "sudo perf stat" cmd += " -e {events} --log-fd 1 -x, -p {pid}".format(events=evcmd, pid=pid) pid, fd = pty.fork() if pid == 0: osexec(cmd) # fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("hhhh", 24, 80, 0, 0)) # resise terminal # disable echo flags = termios.tcgetattr(fd) flags[3] &= ~termios.ECHO termios.tcsetattr(fd, termios.TCSADRAIN, flags) time.sleep(t) ctrl_c = termios.tcgetattr(fd)[-1][termios.VINTR] # get Ctrl+C character os.write(fd, ctrl_c) os.waitpid(pid, 0) raw = b"" while True: try: chunk = os.read(fd, BUF_SIZE) except OSError: break if not chunk: break raw += chunk return PerfData(raw, ann=ann, norm=norm)
def readKeys(): """Waits for keyboard input and calls the method that is mapped to it.""" fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO # dont echo back 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: key = sys.stdin.read(1) if key in control_keys.keys(): control_keys[key]() elif key == 'x': pibot.stop() sys.exit(0) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def __del__(self): if self.LOGGING: # push any remaining output line = self.serial.readline() while line != "": print line, line = self.serial.readline() if AUTOTEST: if self.quiet: sys = __import__("sys") termios = __import__("termios") else: if self.quiet: # for some reason, when our destructor is called sys and termios # are no longer available. So we reimport them. sys = __import__("sys") termios = __import__("termios") fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] | termios.ECHO termios.tcsetattr(fd, termios.TCSADRAIN, new) self.serial.flushInput() self.serial.flushOutput() self.serial.close()
def interact(self): os.write(self.fd, self.readbuffer) old = termios.tcgetattr(self.fd) new = termios.tcgetattr(self.fd) new[3] = new[3] & ~termios.ECHO try: tty.setraw(self.fd) while True: try: rd, wd, ed = select.select([self.ptyfd, self.fd], [], []) except select.error as e: if e.args[0] == 4: continue else: raise for i in rd: if i == self.ptyfd: s = os.read(i, 1024) os.write(self.fd, s) elif i == self.fd: s = os.read(i, 1024) os.write(self.ptyfd, s) except OSError as e: if e.errno == 5: # 使用 print() 会导致下一个 Python 提示符位置不对 os.write(self.fd, '已结束。\r\n'.encode()) else: raise finally: termios.tcsetattr(self.fd, termios.TCSADRAIN, old)
def getChar(): """ !! DOES NOT WORK, IF STDIN WAS "CLOSED" WITH EOF IN THE SAME PROCESS !! Stolen from: http://python4fun.blogspot.de/2008/06/get-key-press-in-python.html """ if (os.name == "nt"): import msvcrt return msvcrt.getch() else: import termios, sys TERMIOS = termios 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) c = None try: c = os.read(fd, 1) finally: termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old) return c
def run_python_interpreter (local_dict): # Pass in the dictionary, for continuity from one session to the next. setquit() try: fd = sys.stdin.fileno(); interacted = False if get_terminal_size(fd)[1] == 0: try: import termios old = termios.tcgetattr(fd) if old[3] & termios.ECHO: # Need to turn off echoing and restore new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ECHO try: termios.tcsetattr(fd, termios.TCSADRAIN, new) interacted = True code.interact(banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()'.", readfunc=readfunc_stdio, local=local_dict) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) except: pass # Don't need to turn off echoing if not interacted: code.interact(banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.", readfunc=readfunc_stdio, local=local_dict) else: # We have a real interactive terminal code.interact(banner="Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.", local=local_dict) except SystemExit as e: global g_builtin_override_called if not g_builtin_override_called: print('Script exited with %s' %(e))
def posix_shell(self): """ Use paramiko channel connect server interactive. 使用paramiko模块的channel,连接后端,进入交互式 """ log_file_f, log_time_f, log = self.get_log() termlog = TermLogRecorder(Admin.objects.get(id=self.user.id)) termlog.setid(log.id) old_tty = termios.tcgetattr(sys.stdin) pre_timestamp = time.time() data = '' input_mode = False try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) self.channel.settimeout(0.0) while True: try: r, w, e = select.select([self.channel, sys.stdin], [], []) flag = fcntl.fcntl(sys.stdin, fcntl.F_GETFL, 0) fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag | os.O_NONBLOCK) except Exception: pass if self.channel in r: try: x = self.channel.recv(10240) if len(x) == 0: break index = 0 len_x = len(x) while index < len_x: try: n = os.write(sys.stdout.fileno(), x[index:]) sys.stdout.flush() index += n except OSError as msg: if msg.errno == errno.EAGAIN: continue now_timestamp = time.time() termlog.write(x) termlog.recoder = False log_time_f.write( '%s %s\n' % (round(now_timestamp - pre_timestamp, 4), len(x))) log_time_f.flush() log_file_f.write(x) log_file_f.flush() pre_timestamp = now_timestamp log_file_f.flush() self.vim_data += x if input_mode: data += x except socket.timeout: pass if sys.stdin in r: try: x = os.read(sys.stdin.fileno(), 4096) except OSError: pass termlog.recoder = True input_mode = True if self.is_output(str(x)): # 如果len(str(x)) > 1 说明是复制输入的 if len(str(x)) > 1: data = x match = self.vim_end_pattern.findall(self.vim_data) if match: if self.vim_flag or len(match) == 2: self.vim_flag = False else: self.vim_flag = True elif not self.vim_flag: self.vim_flag = False data = self.deal_command(data)[0:200] if data is not None: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() data = '' self.vim_data = '' input_mode = False if len(x) == 0: break self.channel.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty) log_file_f.write('End time is %s' % datetime.datetime.now()) log_file_f.close() log_time_f.close() termlog.save() log.filename = termlog.filename log.is_finished = True log.end_time = datetime.datetime.now() log.save()
import pexpect import sys import termios from ansible.module_utils.six import PY2 args = sys.argv[1:] env_vars = { 'ANSIBLE_ROLES_PATH': './roles', 'ANSIBLE_NOCOLOR': 'True', 'ANSIBLE_RETRY_FILES_ENABLED': 'False' } try: backspace = termios.tcgetattr(sys.stdin.fileno())[6][termios.VERASE] except Exception: backspace = b'\x7f' if PY2: log_buffer = sys.stdout else: log_buffer = sys.stdout.buffer os.environ.update(env_vars) # -- Plain pause -- # playbook = 'pause-1.yml' # Case 1 - Contiune with enter pause_test = pexpect.spawn('ansible-playbook',
# Available Dynamixel model on this example : All models using Protocol 2.0 # This example is tested with two Dynamixel PRO 54-200, and two USB2DYNAMIXEL # Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600) # import os if os.name == 'nt': import msvcrt def getch(): return msvcrt.getch().decode() else: import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) def getch(): try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch from dynamixel_sdk import * # Uses Dynamixel SDK library # Control table address ADDR_PRO_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model ADDR_PRO_GOAL_POSITION = 116
def publisher(): rospy.init_node('keyboard_teleop', anonymous=True) pub = rospy.Publisher('/motors_topic', motors_signal, queue_size=10) # define constants : KEY_UP = 65 KEY_DOWN = 66 KEY_RIGHT = 67 KEY_LEFT = 68 KEY_Q = 81 KEY_Q2 = 113 KEY_S = 83 KEY_S2 = 115 MOVE_TIME = 0.01 # define variables : speed = 0.0 rotationalSpeed = 0.0 keyPress = 0 linearDirection = 0 rotationalDirection = 0 linearSpeed = 0 rotationalSpeed = 0 # get char : keyPress = " " fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) motor = motors_signal() oldKey = 0 while True: print(" - AI car manual control \n") print(" > Arrows = move robot \n") print(" > s = stop \n") print(" > q = quit \n") rospy.loginfo("motor left :%i motor right: %i" % (motor.motor_left, motor.motor_right)) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) keyPress = ord(ch) if keyPress != oldKey: os.system('clear') # test command : if (keyPress == KEY_UP): motor.motor_left = 1 motor.motor_right = 1 rospy.loginfo( "\u2191\u2191\u2191\u2191 forward \u2191\u2191\u2191\u2191") elif (keyPress == KEY_DOWN): motor.motor_left = -1 motor.motor_right = -1 rospy.loginfo( "\u2193\u2193\u2193\u2193 backward \u2193\u2193\u2193\u2193") elif (keyPress == KEY_LEFT): motor.motor_left = -1 motor.motor_right = 1 rospy.loginfo( "\u2190\u2190\u2190\u2190 left turn \u2190\u2190\u2190\u2190") elif (keyPress == KEY_RIGHT): motor.motor_left = 1 motor.motor_right = -1 rospy.loginfo( "\u2192\u2192\u2192\u2192 right turn \u2192\u2192\u2192\u2192") elif ((keyPress == KEY_S) or (keyPress == KEY_S2)): motor.motor_left = 0 motor.motor_right = 0 rospy.loginfo( "\u26d4 \u26d4 \u26d4 \u26d4 Stop robot \u26d4 \u26d4 \u26d4 \u26d4" ) elif ((keyPress == KEY_Q) or (keyPress == KEY_Q2)): print("Quiting ...") break pub.publish(motor) oldKey = keyPress
rospy.init_node('tele_key_pub') x = 0 y = 0 z = 0 h = 0 delta = 1 open_p = 0 open_m = 0 chassis = 0 endeff = 0 try: #print(msg) rate = rospy.Rate(500) # 20hz old_attr = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) twist = Twist() ee = EndEffector() state = '2' # 首选遥控器模式 lastState = '0' while not rospy.is_shutdown(): if state == '1': # 键盘模式 if lastState != state: os.system('clear') print(msg)
x2_coefficient = 100 #TODO def getKey(): tty.setraw(sys.stdin.fileno()) rlist, _, _ = select.select([sys.stdin], [], [], 0.1) if rlist: key = sys.stdin.read(1) else: key = '' termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) return key settings = termios.tcgetattr(sys.stdin) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) def manual_shoot(key): if key == 'q': print 'shoot button pressed' turret_thread.shoot_armour() def auto_shoot(pitch_delta, yaw_delta, coord, y_bias, x_bias, Target_lock): if len(coord) > 0: target_coord = util.get_nearest_target(coord, y_bias, x_bias) height = target_coord[3] print pitch_delta, yaw_delta, height
forces[name] -= 100 elif key == '.': name = 'knee' forces[name] = 0 if name is not None: joint = joints[name] message.name = joint['name'] message.axis = joint['axis'] message.force = forces[name] print("%s set to %s" % (message.name, message.force)) publisher.publish(message) 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) print("Making event loop") loop = trollius.get_event_loop() print("Connecting") future = trollius.futures.Future() trollius.ensure_future(connect(future)) loop.run_until_complete(future) publisher = future.result()
def find(cls, path): if not (path.startswith("tty") or path.startswith("com")): return match = PATH.match(path) if match and match.group(1) == "tty": if re.match(r'^(S|ACM|AMA|USB)\d+$', match.group(2)): TTYS = re.compile(r'^tty{}$'.format(match.group(2))) glob = False elif re.match(r'^(S|ACM|AMA|USB)$', match.group(2)): TTYS = re.compile(r'^tty{}\d+$'.format(match.group(2))) glob = True elif re.match(r'^usbserial-\w+$', match.group(2)): TTYS = re.compile(r'^cu\.{}$'.format(match.group(2))) glob = False elif re.match(r'^usbserial$', match.group(2)): TTYS = re.compile(r'^cu\.usbserial-.*$') glob = True elif re.match(r'^.+$', match.group(2)): TTYS = re.compile(r'^{}$'.format(match.group(2))) glob = False else: TTYS = re.compile(r'^(tty(S|ACM|AMA|USB)\d+|cu\.usbserial.*)$') glob = True log.debug(TTYS.pattern) ttys = [fn for fn in os.listdir('/dev') if TTYS.match(fn)] if len(ttys) > 0: # Sort ttys with custom function to correctly order numbers. ttys.sort(key=lambda item: (len(item), item)) log.debug('check: ' + ' '.join('/dev/' + tty for tty in ttys)) # Eliminate tty nodes that are not physically present or # inaccessible by the current user. Propagate IOError when # path designated exactly one device, otherwise just log. for i, tty in enumerate(ttys): try: termios.tcgetattr(open('/dev/%s' % tty)) ttys[i] = '/dev/%s' % tty except termios.error as error: pass except IOError as error: log.debug(error) if not glob: raise error ttys = [tty for tty in ttys if tty.startswith('/dev/')] log.debug('avail: %s', ' '.join([tty for tty in ttys])) return ttys, match.group(3), glob if match and match.group(1) == "com": if re.match(r'^COM\d+$', match.group(2)): return [match.group(2)], match.group(3), False if re.match(r'^\d+$', match.group(2)): return ["COM" + match.group(2)], match.group(3), False if re.match(r'^$', match.group(2)): ports = [p[0] for p in serial.tools.list_ports.comports()] log.debug('serial ports: %s', ' '.join(ports)) return ports, match.group(3), True log.error("invalid port in 'com' path: %r", match.group(2))
def __enter__(self): self.original_stty = termios.tcgetattr(self.stream) tty.setcbreak(self.stream)
import sys import select import tty import termios import serial import time import datetime port = "/dev/ttyUSB1" speed = 921600 time_o = 0 terminator = 0 fd = sys.stdin.fileno() old = termios.tcgetattr(fd) ser = serial.Serial(port, speed, timeout=0, parity=serial.PARITY_NONE) # open serial port #ser = serial.Serial(port, speed, timeout=0, parity=serial.PARITY_NONE, rtscts=1) # open serial port def isData(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) def timest(): ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f') return st try: tty.setcbreak(fd) print('')
def take_control(self): """ This function is a better documented and touched up version of the posix_shell function found in the interactive.py demo script that ships with Paramiko. """ if has_termios: # Get attributes of the shell you were in before going to the # new one original_tty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) # We must set the timeout to 0 so that we can bypass times when # there is no available text to receive self.channel.settimeout(0) # Loop forever until the user exits (i.e. read buffer is empty) while True: select_read, select_write, select_exception = ( select.select([self.channel, sys.stdin], [], [])) # Read any output from the terminal and print it to the # screen. With timeout set to 0, we just can ignore times # when there's nothing to receive. if self.channel in select_read: try: buffer = self.channel.recv(self.buffer_size) if len(buffer) == 0: break sys.stdout.write(buffer) sys.stdout.flush() except socket.timeout: pass # Send any keyboard input to the terminal one byte at a # time if sys.stdin in select_read: buffer = sys.stdin.read(1) if len(buffer) == 0: break self.channel.send(buffer) finally: # Restore the attributes of the shell you were in termios.tcsetattr(sys.stdin, termios.TCSADRAIN, original_tty) else: def writeall(sock): while True: buffer = sock.recv(self.buffer_size) if len(buffer) == 0: break sys.stdout.write(buffer) sys.stdout.flush() writer = threading.Thread(target=writeall, args=(self.channel, )) writer.start() try: while True: buffer = sys.stdin.read(1) if len(buffer) == 0: break self.channel.send(buffer) # User has hit Ctrl+Z or F6 except EOFError: pass
def __init__(self, testload, speed=4800, databits=8, parity='N', stopbits=1, progress=lambda x: None): super(FakePTY, self).__init__(testload, progress) # Allow Serial: header to be overridden by explicit speed. if self.testload.serial: (speed, databits, parity, stopbits) = self.testload.serial self.speed = speed baudrates = { 0: termios.B0, 50: termios.B50, 75: termios.B75, 110: termios.B110, 134: termios.B134, 150: termios.B150, 200: termios.B200, 300: termios.B300, 600: termios.B600, 1200: termios.B1200, 1800: termios.B1800, 2400: termios.B2400, 4800: termios.B4800, 9600: termios.B9600, 19200: termios.B19200, 38400: termios.B38400, 57600: termios.B57600, 115200: termios.B115200, 230400: termios.B230400, } (self.fd, self.slave_fd) = pty.openpty() self.byname = os.ttyname(self.slave_fd) os.chmod(self.byname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH) (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr( self.slave_fd) cc[termios.VMIN] = 1 cflag &= ~(termios.PARENB | termios.PARODD | termios.CRTSCTS) cflag |= termios.CREAD | termios.CLOCAL iflag = oflag = lflag = 0 iflag &= ~ (termios.PARMRK | termios.INPCK) cflag &= ~ (termios.CSIZE | termios.CSTOPB | termios.PARENB | termios.PARODD) if databits == 7: cflag |= termios.CS7 else: cflag |= termios.CS8 if stopbits == 2: cflag |= termios.CSTOPB # Warning: attempting to set parity makes Fedora lose its cookies if parity == 'E': iflag |= termios.INPCK cflag |= termios.PARENB elif parity == 'O': iflag |= termios.INPCK cflag |= termios.PARENB | termios.PARODD ispeed = ospeed = baudrates[speed] try: termios.tcsetattr(self.slave_fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) except termios.error: raise TestLoadError("error attempting to set serial mode to %s " " %s%s%s" % (speed, databits, parity, stopbits))
Script which prompts for username and password, and authenticates with the DCSO Portal. If 2FA is set up, it will also ask for TOTP code. """ try: if os.name == 'nt': import msvcrt def getch(): return msvcrt.getch().decode() else: import tty import termios fd = sys.stdin.fileno() prev = termios.tcgetattr(fd) def getch(): try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, prev) return ch def getpass(prompt): placeholder = '\N{MIDDLE DOT}' print(prompt, end='', flush=True) import curses
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 setup_tty(self): if os.isatty(sys.stdin.fileno()): self.log.debug('putting tty into raw mode') self.old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin)
# import socket programming library import socket # import thread module from _thread import * import threading from time import sleep import os import termios, sys, os import sys, termios, atexit import select as sl from select import select # save the terminal settings fd = sys.stdin.fileno() new_term = termios.tcgetattr(fd) old_term = termios.tcgetattr(fd) TERMIOS = termios print_lock = threading.Lock() ventilator = 0 led_status = 0 door_status = 0 ep2S = [0, 0] # %fan,led_status,door_status,button ep2A = [0, 0] ep1S = [0, 0] # temperature,light_buld,place_to_start ep1A = [0, 0] # switch to normal terminal def set_normal_term(): termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
def __init__(self, fd=0): self._fd = fd self._old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, new)
# Constants NAME = "MySQL Utilities - mysqlfailover " DESCRIPTION = "mysqlfailover - automatic replication health monitoring and failover" USAGE = "%prog --master=roo@localhost --discover-slaves-login=root " + \ "--candidates=root@host123:3306,root@host456:3306 " _DATE_FORMAT = '%Y-%m-%d %H:%M:%S %p' _DATE_LEN = 22 # Setup a terminal signal handler for SIGNIT # Must use SetConsoleCtrlHandler function on Windows! # If posix, save old terminal settings so we can restore them on exit. try: # Only valid for *nix systems. import tty, termios old_terminal_settings = termios.tcgetattr(sys.stdin) except: # Ok to fail for Windows pass def set_signal_handler(func): # If posix, restore old terminal settings. if os.name == "nt": from ctypes import windll windll.kernel32.SetConsoleCtrlHandler(func, True) # Install SIGTERM signal handler else: signal.signal(signal.SIGTERM, func)
if len(argv) > 1: myFile = argv[1] else: myFile = '~/.2fa' myConf = totp.Config(myFile) myTTY = '/dev/' + environ['PAM_TTY'] setresuid(0, 0, 0) totp.setCatch(myConf.options['timer']) with open(myTTY, 'w') as handle: handle.write('Challenge: ') with open(myTTY) as handle: old = tcgetattr(handle.fileno()) new = tcgetattr(handle.fileno()) new[3] = new[3] & ~ECHO try: tcsetattr(handle.fileno(), DRAIN, new) while True: myCode = handle.readline().rstrip() if len(myCode): break finally: tcsetattr(handle.fileno(), DRAIN, old) with open(myTTY, 'w') as handle: handle.write('\n') if myConf.authenticate(myCode):
def __init__(self, baudrate=115200, device='/dev/ttyUSB0', rst=0, clr=False): self.DEVICE = device self.BAUDRATE = baudrate self.ESCAPECHAR = "\033" self.VERSION = "5.1.4" self.ShutdownReceiver = False self.ReceiverToStdout = True self.DefaultTimeout = 0.1 self.width, self.height = shutil.get_terminal_size() self.colors = clr; if clr is True: self.TCLR = dict( NORMAL = '\033[0m', RED = '\033[1;31m', BLUE = '\033[1;34m', YELLOW = '\033[1;33m', WHITE = '\033[1;37m' ) else: self.TCLR = dict( NORMAL = '', RED = '', BLUE = '', YELLOW = '', WHITE = '' ) print("\n"+self.TCLR['RED']+"--[ "+self.TCLR['BLUE']+"MicroPython terminal "+self.TCLR['RED']+" ver. "+self.TCLR['BLUE']+self.VERSION + self.TCLR['RED']+" ]-- "+self.TCLR['NORMAL']) print(self.TCLR['RED']+"--[ "+self.TCLR['BLUE']+"Press ESC twice for command mode"+self.TCLR['RED']+" ]-- "+self.TCLR['NORMAL']+"\n") # Open remote terminal device try: self.uart = serial.Serial( port = self.DEVICE, baudrate= self.BAUDRATE, bytesize= serial.EIGHTBITS, parity = serial.PARITY_NONE, stopbits= serial.STOPBITS_ONE, timeout = self.DefaultTimeout, xonxoff = 0, rtscts = 0, interCharTimeout=None ) if rst: self.uart.dtr = False time.sleep(0.1) self.uart.dtr = True else: self.uart.write(b'\r\n') time.sleep(0.1) #self.uart.dtr = False #self.uart.rts = False #time.sleep(0.1) except Exception as e: raise Exception(self.TCLR['RED']+"Accessing "+self.TCLR['WHITE'] + self.DEVICE + " "+self.TCLR['RED']+"failed\r\n"+self.TCLR['WHITE']+"PyTerm exit"+self.TCLR['NORMAL']+"\r\n") # Setup local terminal self.stdinfd = sys.stdin.fileno() self.oldstdinsettings = termios.tcgetattr(self.stdinfd) tty.setraw(self.stdinfd) # from now on, end-line must be "\r\n" # Start receiver thread self.ReceiverThread = Thread(target=self.ReceiveData, args=(self.uart, False)) self.ReceiverThread.start() # this is the main loop of this software try: self.HandleUnbufferedUserInput(); except Exception as e: print("\r\n"+self.TCLR['RED']+"Error: failed with the following exception:"+self.TCLR['NORMAL']+"\r\n") print(e, "\r\n") # Shutdown receiver thread self.ShutdownReceiver = True if self.ReceiverThread.isAlive(): self.ReceiverThread.join() # Clean up everything termios.tcsetattr(self.stdinfd, termios.TCSADRAIN, self.oldstdinsettings) self.uart.close()
from sensor_msgs.msg import LaserScan from sensor_msgs.msg import Range from nav_msgs.msg import Odometry import numpy as np import matplotlib.pyplot as plt import matplotlib, time import threading from math import atan2, sqrt, pow, fabs, pi, tan from matplotlib.pyplot import figure, show, rc, draw import tf import sys, select, termios, tty from tf.transformations import euler_from_quaternion, euler_matrix MSG = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] i = 0 settings = termios.tcgetattr(sys.stdin) # for getKey() X_points = np.multiply(68.58 / 2, np.mat('-1 -1 1 1;1 -1 -1 1;0 0 0 0')) a = np.mat(np.ones((1, 4))) X_points = np.bmat('X_points; a') Kc = np.mat( ' 1058.3 0 436.85;0 -1091.6 117.55; 0 0 1' ) def publish_pointestimates(servoang): global X_points, Kc, MSG #MSG[9]=726 #servoang=0 t = np.mat('-1.6991; 51.3061; -83.5694') t[2, :] = t[2, :] + MSG[9] #print t
def disable_echo(self): fileno = sys.stdin.fileno() self.old_termio_settings = termios.tcgetattr(fileno) tty.setcbreak(fileno)
def prep(self): old(self) f = sys.stdin.fileno() a = termios.tcgetattr(f) a[1] |= 1 # Turn on postprocessing (OPOST) termios.tcsetattr(f, termios.TCSANOW, a)
def main(): prog_version = pkg_resources.require("spotify-ripper")[0].version # load config file, overwriting any defaults defaults = { "bitrate": "320", "quality": "320", "comp": "10", "vbr": "0", "partial_check": "weak", } defaults = load_config(defaults) spotipy_envs = [ "SPOTIPY_CLIENT_ID", "SPOTIPY_CLIENT_SECRET", "SPOTIPY_REDIRECT_URI" ] for spotipy_env in spotipy_envs: if spotipy_env not in os.environ: value = defaults.get(spotipy_env.lower()) if value: os.environ[spotipy_env] = value parser = argparse.ArgumentParser( prog='spotify-ripper', description= 'Rips Spotify URIs to media files with tags and album covers') # create group to prevent user from using both the -l and -u option is_user_set = defaults.get('user') is not None is_last_set = defaults.get('last') is True if is_user_set or is_last_set: if is_user_set and is_last_set: print("spotify-ripper: error: one of the arguments -u/--user " "-l/--last is required") sys.exit(1) else: group = parser.add_mutually_exclusive_group(required=False) else: group = parser.add_mutually_exclusive_group(required=True) encoding_group = parser.add_mutually_exclusive_group(required=False) # set defaults parser.set_defaults(**defaults) # Positional arguments parser.add_argument( 'uri', nargs="+", help= 'One or more Spotify URI(s) (either URI, a file of URIs or a search query)' ) # Optional arguments parser.add_argument( '-a', '--ascii', action='store_true', help= 'Convert the file name and the metadata tags to ASCII encoding [Default=utf-8]' ) encoding_group.add_argument( '--aac', action='store_true', help='Rip songs to AAC format with FreeAAC instead of MP3') encoding_group.add_argument( '--aiff', action='store_true', help='Rip songs to lossless AIFF encoding instead of MP3') encoding_group.add_argument( '--alac', action='store_true', help='Rip songs to Apple Lossless format instead of MP3') parser.add_argument( '--all-artists', action='store_true', help= 'Store all artists, rather than just the main artist, in the track\'s metadata tag' ) parser.add_argument( '--artist-album-type', help= 'Only load albums of specified types when passing a Spotify artist URI [Default=album,single,ep,compilation,appears_on]' ) parser.add_argument( '--artist-album-market', help= 'Only load albums with the specified ISO2 country code when passing a Spotify artist URI. You may get duplicate albums if not set. [Default=any]' ) parser.add_argument( '-A', '--ascii-path-only', action='store_true', help= 'Convert the file name (but not the metadata tags) to ASCII encoding [Default=utf-8]' ) parser.add_argument('-b', '--bitrate', help='CBR bitrate [Default=320]') parser.add_argument('-c', '--cbr', action='store_true', help='CBR encoding [Default=VBR]') parser.add_argument( '--comp', help='compression complexity for FLAC and Opus [Default=Max]') parser.add_argument( '--comment', help= 'Set comment metadata tag to all songs. Can include same tags as --format.' ) parser.add_argument( '--cover-file', help= 'Save album cover image to file name (e.g "cover.jpg") [Default=embed]' ) parser.add_argument( '--cover-file-and-embed', metavar="COVER_FILE", help='Same as --cover-file but embeds the cover image too') parser.add_argument( '-d', '--directory', help='Base directory where ripped MP3s are saved [Default=cwd]') parser.add_argument('--fail-log', help="Logs the list of track URIs that failed to rip") encoding_group.add_argument( '--flac', action='store_true', help='Rip songs to lossless FLAC encoding instead of MP3') parser.add_argument( '-f', '--format', help='Save songs using this path and filename structure (see README)') parser.add_argument( '--format-case', choices=['upper', 'lower', 'capitalize'], help= 'Convert all words of the file name to upper-case, lower-case, or capitalized' ) parser.add_argument( '--flat', action='store_true', help='Save all songs to a single directory (overrides --format option)' ) parser.add_argument( '--flat-with-index', action='store_true', help= 'Similar to --flat [-f] but includes the playlist index at the start of the song file' ) parser.add_argument( '-g', '--genres', choices=['artist', 'album'], help= 'Attempt to retrieve genre information from Spotify\'s Web API [Default=skip]' ) parser.add_argument( '--grouping', help= 'Set grouping metadata tag to all songs. Can include same tags as --format.' ) encoding_group.add_argument( '--id3-v23', action='store_true', help='Store ID3 tags using version v2.3 [Default=v2.4]') parser.add_argument( '--large-cover-art', action='store_true', help= 'Attempt to retrieve 640x640 cover art from Spotify\'s Web API [Default=300x300]' ) group.add_argument('-l', '--last', action='store_true', help='Use last login credentials') parser.add_argument( '-L', '--log', help='Log in a log-friendly format to a file (use - to log to stdout)') encoding_group.add_argument( '--pcm', action='store_true', help='Saves a .pcm file with the raw PCM data instead of MP3') encoding_group.add_argument( '--mp4', action='store_true', help= 'Rip songs to MP4/M4A format with Fraunhofer FDK AAC codec instead of MP3' ) parser.add_argument('--normalize', action='store_true', help='Normalize volume levels of tracks') parser.add_argument( '-na', '--normalized-ascii', action='store_true', help= 'Convert the file name to normalized ASCII with unicodedata.normalize (NFKD)' ) parser.add_argument('-o', '--overwrite', action='store_true', help='Overwrite existing MP3 files [Default=skip]') encoding_group.add_argument( '--opus', action='store_true', help='Rip songs to Opus encoding instead of MP3') parser.add_argument( '--partial-check', choices=['none', 'weak', 'strict'], help= 'Check for and overwrite partially ripped files. "weak" will err on the side of not re-ripping the file if it is unsure, whereas "strict" will re-rip the file [Default=weak]' ) parser.add_argument('-p', '--password', help='Spotify password [Default=ask interactively]') parser.add_argument( '--play-token-resume', metavar="RESUME_AFTER", help= 'If the \'play token\' is lost to a different device using the same Spotify account, the script will wait a specified amount of time before restarting. This argument takes the same values as --resume-after [Default=abort]' ) parser.add_argument('--playlist-m3u', action='store_true', help='create a m3u file when ripping a playlist') parser.add_argument('--playlist-wpl', action='store_true', help='create a wpl file when ripping a playlist') parser.add_argument( '--playlist-sync', action='store_true', help='Sync playlist songs (rename and remove old songs)') parser.add_argument( '--plus-pcm', action='store_true', help='Saves a .pcm file in addition to the encoded file (e.g. mp3)') parser.add_argument( '--plus-wav', action='store_true', help='Saves a .wav file in addition to the encoded file (e.g. mp3)') parser.add_argument( '-q', '--vbr', help='VBR quality setting or target bitrate for Opus [Default=0]') parser.add_argument('-Q', '--quality', choices=['160', '320', '96'], help='Spotify stream bitrate preference [Default=320]') parser.add_argument( '--remove-offline-cache', action='store_true', help= 'Remove libspotify\'s offline cache directory after the rip is complete to save disk space' ) parser.add_argument( '--resume-after', help= 'Resumes script after a certain amount of time has passed after stopping (e.g. 1h30m). Alternatively, accepts a specific time in 24hr format to start after (e.g 03:30, 16:15). Requires --stop-after option to be set' ) parser.add_argument( '-R', '--replace', nargs="+", required=False, help= 'pattern to replace the output filename separated by "/". The following example replaces all spaces with "_" and all "-" with ".": spotify-ripper --replace " /_" "\-/." uri' ) parser.add_argument('-s', '--strip-colors', action='store_true', help='Strip coloring from output [Default=colors]') parser.add_argument( '--stereo-mode', choices=['j', 's', 'f', 'd', 'm', 'l', 'r'], help='Advanced stereo settings for Lame MP3 encoder only') parser.add_argument( '--stop-after', help= 'Stops script after a certain amount of time has passed (e.g. 1h30m). Alternatively, accepts a specific time in 24hr format to stop after (e.g 03:30, 16:15)' ) parser.add_argument( '--timeout', type=int, help= 'Override the PySpotify timeout value in seconds (Default=10 seconds)') group.add_argument('-u', '--user', help='Spotify username') parser.add_argument('-V', '--version', action='version', version=prog_version) encoding_group.add_argument( '--wav', action='store_true', help='Rip songs to uncompressed WAV file instead of MP3') parser.add_argument( '--windows-safe', action='store_true', help= 'Make filename safe for Windows file system (truncate filename to 255 characters)' ) encoding_group.add_argument( '--vorbis', action='store_true', help='Rip songs to Ogg Vorbis encoding instead of MP3') parser.add_argument( '-r', '--remove-from-playlist', action='store_true', help='Delete tracks from playlist after successful ripping [Default=no]' ) args = parser.parse_args() init_util_globals(args) # kind of a hack to get colorama stripping to work when outputting # to a file instead of stdout. Taken from initialise.py in colorama def wrap_stream(stream, convert, strip, autoreset, wrap): if wrap: wrapper = AnsiToWin32(stream, convert=convert, strip=strip, autoreset=autoreset) if wrapper.should_wrap(): stream = wrapper.stream return stream args.has_log = args.log is not None if args.has_log: if args.log == "-": init(strip=True) else: encoding = "ascii" if args.ascii else "utf-8" log_file = codecs.open(enc_str(args.log), 'a', encoding) sys.stdout = wrap_stream(log_file, None, True, False, True) else: init(strip=True if args.strip_colors else None) if args.ascii_path_only is True: args.ascii = True if args.wav: args.output_type = "wav" elif args.pcm: args.output_type = "pcm" elif args.flac: args.output_type = "flac" if args.comp == "10": args.comp = "8" elif args.vorbis: args.output_type = "ogg" if args.vbr == "0": args.vbr = "9" elif args.opus: args.output_type = "opus" if args.vbr == "0": args.vbr = "320" elif args.aac: args.output_type = "aac" if args.vbr == "0": args.vbr = "500" elif args.mp4: args.output_type = "m4a" if args.vbr == "0": args.vbr = "5" elif args.alac: args.output_type = "alac.m4a" elif args.aiff: args.output_type = "aiff" else: args.output_type = "mp3" # check that encoder tool is available encoders = { "flac": ("flac", "flac"), "aiff": ("sox", "sox"), "aac": ("faac", "faac"), "ogg": ("oggenc", "vorbis-tools"), "opus": ("opusenc", "opus-tools"), "mp3": ("lame", "lame"), "m4a": ("fdkaac", "aac-enc"), "alac.m4a": ("ffmpeg", "ffmpeg"), } if args.output_type in encoders.keys(): encoder = encoders[args.output_type][0] if which(encoder) is None: print(Fore.RED + "Missing dependency '" + encoder + "'. Please install '" + encoders[args.output_type][1] + "'." + Fore.RESET) sys.exit(1) # format string if args.flat: args.format = "{artist} - {track_name}.{ext}" elif args.flat_with_index: args.format = "{idx:3} - {artist} - {track_name}.{ext}" elif args.format is None: args.format = "{album_artist}/{album}/{artist} - {track_name}.{ext}" # print some settings print(Fore.GREEN + "Spotify Ripper - v" + prog_version + Fore.RESET) def encoding_output_str(): if args.output_type == "wav": return "WAV, Stereo 16bit 44100Hz" elif args.output_type == "pcm": return "Raw Headerless PCM, Stereo 16bit 44100Hz" else: if args.output_type == "flac": return "FLAC, Compression Level: " + args.comp elif args.output_type == "aiff": return "AIFF" elif args.output_type == "alac.m4a": return "Apple Lossless (ALAC)" elif args.output_type == "ogg": codec = "Ogg Vorbis" elif args.output_type == "opus": codec = "Opus" elif args.output_type == "mp3": codec = "MP3" elif args.output_type == "m4a": codec = "MPEG4 AAC" elif args.output_type == "aac": codec = "AAC" else: codec = "Unknown" if args.cbr: return codec + ", CBR " + args.bitrate + " kbps" else: return codec + ", VBR " + args.vbr print(Fore.YELLOW + " Encoding output:\t" + Fore.RESET + encoding_output_str()) print(Fore.YELLOW + " Spotify bitrate:\t" + Fore.RESET + args.quality + " kbps") def unicode_support_str(): if args.ascii_path_only: return "Unicode tags, ASCII file path" elif args.ascii: return "ASCII only" else: return "Yes" # check that --stop-after and --resume-after options are valid if args.stop_after is not None and \ parse_time_str(args.stop_after) is None: print(Fore.RED + "--stop-after option is not valid" + Fore.RESET) sys.exit(1) if args.resume_after is not None and \ parse_time_str(args.resume_after) is None: print(Fore.RED + "--resume-after option is not valid" + Fore.RESET) sys.exit(1) if args.play_token_resume is not None and \ parse_time_str(args.play_token_resume) is None: print(Fore.RED + "--play_token_resume option is not valid" + Fore.RESET) sys.exit(1) print(Fore.YELLOW + " Unicode support:\t" + Fore.RESET + unicode_support_str()) print(Fore.YELLOW + " Output directory:\t" + Fore.RESET + base_dir()) print(Fore.YELLOW + " Settings directory:\t" + Fore.RESET + settings_dir()) print(Fore.YELLOW + " Format String:\t" + Fore.RESET + args.format) print(Fore.YELLOW + " Overwrite files:\t" + Fore.RESET + ("Yes" if args.overwrite else "No")) ripper = Ripper(args) ripper.start() # try to listen for terminal resize events # (needs to be called on main thread) if not args.has_log: ripper.progress.handle_resize() signal.signal(signal.SIGWINCH, ripper.progress.handle_resize) def hasStdinData(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) def abort(set_logged_in=False): ripper.abort_rip() if set_logged_in: ripper.ripper_continue.set() ripper.join() sys.exit(1) def skip(): if ripper.ripping.is_set(): ripper.skip.set() # check if we were passed a file name or search def check_uri_args(): if len(args.uri) == 1 and path_exists(args.uri[0]): encoding = "ascii" if args.ascii else "utf-8" args.uri = [ line.strip() for line in codecs.open(enc_str(args.uri[0]), 'r', encoding) if not line.strip().startswith("#") and len(line.strip()) > 0 ] elif len(args.uri) == 1 and not args.uri[0].startswith("spotify:"): args.uri = [list(ripper.search_query(args.uri[0]))] # login and uri_parse on main thread to catch any KeyboardInterrupt try: if not ripper.login(): print(Fore.RED + "Encountered issue while logging into " "Spotify, aborting..." + Fore.RESET) abort(set_logged_in=True) else: check_uri_args() ripper.ripper_continue.set() except (KeyboardInterrupt, Exception) as e: if not isinstance(e, KeyboardInterrupt): print(str(e)) print("\n" + Fore.RED + "Aborting..." + Fore.RESET) abort(set_logged_in=True) # wait for ripping thread to finish if not args.has_log: try: stdin_settings = termios.tcgetattr(sys.stdin) except termios.error: stdin_settings = None try: if not args.has_log and stdin_settings: tty.setcbreak(sys.stdin.fileno()) while ripper.is_alive(): schedule.run_pending() # check if the escape button was pressed if not args.has_log and hasStdinData(): c = sys.stdin.read(1) if c == '\x1b': skip() ripper.join(0.1) except (KeyboardInterrupt, Exception) as e: if not isinstance(e, KeyboardInterrupt): print(str(e)) print("\n" + Fore.RED + "Aborting..." + Fore.RESET) abort() finally: if not args.has_log and stdin_settings: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, stdin_settings)
def __init__(self): self.key_pub = rospy.Publisher('keys', String, queue_size=1) #rospy.init_node("keyboard_driver") self.old_attr = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) print "Publishing keystrokes. Press Ctrl-C to exit.."
import serial from datetime import datetime import time import termios import os import signal # Timeout (sec): for how long will Pi wait for Arduino? TIME_OUT = 3 #GPS path = '/dev/cycle_gps' with open(path) as f: attrs = termios.tcgetattr(f) attrs[2] = attrs[2] & ~termios.HUPCL termios.tcsetattr(f, termios.TCSAFLUSH, attrs) #GPS ser2 = serial.Serial(port=path, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) #arduino path2 = '/dev/cycle_arduino' with open(path2) as f: attrs = termios.tcgetattr(f) attrs[2] = attrs[2] & ~termios.HUPCL termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
print "\nSpeed is now %f." % speed elif key == KEY_SEEK_REVERSE: global seek_reverse seek_reverse = True elif key == KEY_SEEK_FORWARD: global seek_forward seek_forward = True write_progress.last_note = shm.notes.note.get() # Setup terminal for key by key input old_options = termios.tcgetattr(sys.stdin) new_options = old_options[:] new_options[3] &= ~(termios.ECHO | termios.ICANON) termios.tcsetattr(sys.stdin, termios.TCSANOW, new_options) try: #Status indication total_time_diff = timediff(log_start_time, log_end_time) input_thread = Thread(target=process_input) input_thread.daemon = True input_thread.start() while not parse.finished_parsing(): current_diff = timediff(log_start_time, cur_time) percent = int(round(100.0 * current_diff / total_time_diff))
def __init__(self, fileno): self.fileno = fileno self.attrs_before = termios.tcgetattr(fileno)
def del_flow(self, flow_ids, forced=False): """ Return True or False to del a flow from given list. """ if len(flow_ids) <= 0: return False if not self.flows: self.load_flows() del_flows = [] fd = sys.stdin.fileno() old = termios.tcgetattr(fd) for flow_id in flow_ids: if isinstance(flow_id, str) and flow_id.isdigit(): flow_id = int(flow_id) else: continue if flow_id >= len(self.flows): continue else: del_flow = self.flows[flow_id] if forced: del_flows.append(del_flow) else: Flow.banner_output() del_flow.fmt_output() output('Del the flow? [Y/n]: ') new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON try: termios.tcsetattr(fd, termios.TCSADRAIN, new) while True: in_ch = sys.stdin.read(1) if in_ch == 'n' or in_ch == 'N': output('\tCancel the deletion.\n') break elif in_ch == 'y' or in_ch == 'Y' or in_ch != '\n': del_flows.append(del_flow) output('\n') break else: output('\nWrong, please input [Y/n]: ') continue finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) if not del_flows: return False self.load_flows(True) f = open(self.flows_db, 'r') while True: lines = f.readlines(1000) if not lines: break for line in lines: flow = self._parse_flow(line) if flow in del_flows: del_matches = line.replace(',', ' ').split() del_matches = \ filter(lambda m: not (m.startswith("cookie=") or m.startswith("actions=")), del_matches) del_cmd = "ovs-ofctl --strict del-flows %s %s" \ % (self.bridge, ','.join(del_matches)) err = Popen(del_cmd, stdout=PIPE, stderr=PIPE, shell=True).communicate()[1] if err: error("Error when delflow <%s> in bridge %s\n" % (','.join(del_matches), self.bridge)) error(err) return False f.close() self.load_flows() return True
def main(): parser = argparse.ArgumentParser( description='Access a Xinu backend with GDB support. By default this ' 'program will connect to the first available free backend, ' 'upload the image file called "xinu" from the current directory ' 'and powercycle the backend.\n\n' 'You can specify the name of the image file, the backend and ' 'choose whether you want to powercycle or upload.') parser.add_argument('--status', '-s', dest='status', action='store_true', help='print out status of backends and exit') parser.add_argument( '--type', '-t', '--class', '-c', dest='type', action='store', default='quark', help='the type of backend board to connect to (default=quark)') parser.add_argument('--xinu', '-x', dest='xinu_file', action='store', default='xinu', help='the xinu image file to upload and debug\n' '(default="./xinu")') parser.add_argument("--no-powercycle", "-p", action='store_false', dest='powercycle', help='do not power cycle the backend when connecting') parser.add_argument("--no-upload", "-u", action='store_false', dest='upload', help='do not upload the xinu image before connecting') parser.add_argument( 'backend', metavar='BACKEND', type=str, nargs='?', default=None, help='optionally specify a backend board to connect to') args = parser.parse_args() backend_type = args.type if 'CS_CLASS' in os.environ: backend_type = os.environ['CS_CLASS'] backend_servers = get_backend_servers(backend_class=backend_type) if args.status: seen = set() row_format = "| {:<12}| {:<10}| {:<12}| {:<10}|" print(row_format.format("Backend", "Type", "User", "Time")) print("|-" + ('-' * 12) + '+-' + ('-' * 10) + '+-' + ('-' * 12) + '+-' + ('-' * 10) + '|') for server in backend_servers: for backend in server.backends: if backend.name not in seen: print( row_format.format(backend.name, backend.type, str(backend.user), str(backend.time))) seen.add(backend.name) return if args.backend is None: server, backend = get_free_backend(backend_servers) else: server, backend = get_specific_backend(backend_servers, args.backend) if server is None: print("Backend {} not found, use --status to list backends".format( args.backend)) return if backend.user is not None: print("Backend {} is in use by {}".format(backend.name, backend.user)) return if args.upload: print("Uploading image file") with open(args.xinu_file, 'rb') as f: upload_image(server.addr, backend, f) print("Done uploading image") connection_string = get_connection_string(command="connect", server=backend.name, backend_class=backend.type) response, addr = send_command(server.addr, connection_string) addr = addr[0] port = parse_port(response) print("Connecting to {}, backend: {}, address: {}:{}".format( server.name, backend.name, addr, port)) # Establish a tcp connection on the provided port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((addr, port)) xinu_sock = s.makefile("rb", 0) gdb_handler = GDBRequestHandler(s) print("GDB server listening on localhost:{}".format(gdb_handler.port)) print("You can connect automatically with: gdb -x ~/.xkdb") with open("{}/.xkdb".format(expanduser('~')), "w") as f: f.write("file {}.elf\n".format(abspath(args.xinu_file))) f.write("set tcp auto-retry on\n") f.write("set tcp connect-timeout 120\n") f.write('print ""\n') f.write('print ""\n') f.write('print "██╗ ██╗██╗ ██╗██████╗ ██████╗"\n') f.write('print "╚██╗██╔╝██║ ██╔╝██╔══██╗██╔══██╗"\n') f.write('print " ╚███╔╝ █████╔╝ ██║ ██║██████╔╝"\n') f.write('print " ██╔██╗ ██╔═██╗ ██║ ██║██╔══██╗"\n') f.write('print "██╔╝ ██╗██║ ██╗██████╔╝██████╔╝"\n') f.write('print "╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═════╝ "\n') f.write('print ""\n') f.write('print ""\n') f.write( 'print "***** Connecting to xinu - please wait until fully booted *****"\n' ) f.write('print ""\n') f.write("target remote localhost:{}\n".format(gdb_handler.port)) if args.powercycle: print("[i] Power cycling backend") powercycle(server.addr, backend) # perserve previous terminal settings fd = sys.stdin.fileno() prev_settings = termios.tcgetattr(fd) # set terminal to raw mode for stdin tty.setcbreak(sys.stdin) # register an exit handler for resetting the terminal atexit.register( lambda: termios.tcsetattr(fd, termios.TCSADRAIN, prev_settings)) while True: # poll to see if there is user input (read_in, _, _) = select.select([xinu_sock, sys.stdin], [], []) # handle stdin if sys.stdin in read_in: user_input = sys.stdin.read(1) xinu_sock.write(user_input) # handle socket elif xinu_sock in read_in: byte = xinu_sock.read(1) if byte == '\02': handle_gdb_msg(xinu_sock, gdb_handler) else: sys.stdout.write(byte) sys.stdout.flush()