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 runDebug(self, exc_info): if flags.can_touch_runtime_system("switch console") and self._intf_tty_num != 1: iutil.vtActivate(1) iutil.eintr_retry_call(os.open, "/dev/console", os.O_RDWR) # reclaim stdin iutil.eintr_ignore(os.dup2, 0, 1) # reclaim stdout iutil.eintr_ignore(os.dup2, 0, 2) # reclaim stderr # ^ # | # +------ dup2 is magic, I tells ya! # bring back the echo import termios si = sys.stdin.fileno() attr = termios.tcgetattr(si) attr[3] = attr[3] & termios.ECHO termios.tcsetattr(si, termios.TCSADRAIN, attr) print("\nEntering debugger...") print("Use 'continue' command to quit the debugger and get back to " "the main window") import pdb pdb.post_mortem(exc_info.stack) if flags.can_touch_runtime_system("switch console") and self._intf_tty_num != 1: iutil.vtActivate(self._intf_tty_num)
def __exit__(self, exc_type, exception, traceback): # If termios was avaialble, restore old settings after the # with block if self.old_cfg: import termios termios.tcsetattr( self.stream.fileno(), termios.TCSADRAIN, self.old_cfg)
def __init__(self, port): try: import termios fd = open(port) tmp = termios.tcgetattr(fd.fileno()) termios.tcsetattr(fd.fileno(), termios.TCSADRAIN, tmp) fd.close() except (ImportError, IOError, termios.error): pass self._msg = FWRTSSMessage() self._ser = None self._buf = [] self._crc = crcmod.mkCrcFun(0x104c11db7, initCrc=0xFFFFFFFF, xorOut=0, rev=False) try: self._ser = serial.Serial(port, 115200) self._ser.flush() self._ser.flushInput() self._ser.flushOutput() self._ser.timeout = 0.2 except serial.serialutil.SerialException, e: raise FWRTSSError(str(e))
def getch(): try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
def getChar(): import termios, fcntl, sys, os, select fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = oldterm[:] 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: r, w, e = select.select([fd], [], []) if r: c = sys.stdin.read(1) print "Got character", repr(c) if c == "q": return finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c
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 trigger_loop(): is_posix = sys.platform != 'win32' old_count = workflow.pages_shot if is_posix: import select old_settings = termios.tcgetattr(sys.stdin) data_available = lambda: (select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])) read_char = lambda: sys.stdin.read(1) else: data_available = msvcrt.kbhit read_char = msvcrt.getch try: if is_posix: tty.setcbreak(sys.stdin.fileno()) while True: time.sleep(0.01) if workflow.pages_shot != old_count: old_count = workflow.pages_shot refresh_stats() if not data_available(): continue char = read_char() if char in tuple(capture_keys) + ('r', ): workflow.capture(retake=(char == 'r')) refresh_stats() elif char == 'f': break finally: if is_posix: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
def _posix_shell(self, chan): oldtty = termios.tcgetattr(stdin) try: # tty.setraw(stdin.fileno()) # tty.setcbreak(stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select([chan, stdin], [], []) if chan in r: try: x = chan.recv(128) if len(x) == 0: print "\r\n*** EOF\r\n", break stdout.write(x) stdout.flush() # print len(x), repr(x) except socket.timeout: pass if stdin in r: x = stdin.read(1) if len(x) == 0: break chan.sendall(x) finally: termios.tcsetattr(stdin, termios.TCSADRAIN, oldtty)
def __init__(self, serialport, bps): """Takes the string name of the serial port (e.g. "/dev/tty.usbserial","COM1") and a baud rate (bps) and connects to that port at that speed and 8N1. Opens the port in fully raw mode so you can send binary data. """ self.fd = os.open(serialport, os.O_RDWR | os.O_NOCTTY | os.O_NDELAY) attrs = termios.tcgetattr(self.fd) bps_sym = bps_to_termios_sym(bps) # Set I/O speed. attrs[ISPEED] = bps_sym attrs[OSPEED] = bps_sym # 8N1 attrs[CFLAG] &= ~termios.PARENB attrs[CFLAG] &= ~termios.CSTOPB attrs[CFLAG] &= ~termios.CSIZE attrs[CFLAG] |= termios.CS8 # No flow control attrs[CFLAG] &= ~termios.CRTSCTS # Turn on READ & ignore contrll lines. attrs[CFLAG] |= termios.CREAD | termios.CLOCAL # Turn off software flow control. attrs[IFLAG] &= ~(termios.IXON | termios.IXOFF | termios.IXANY) # Make raw. attrs[LFLAG] &= ~(termios.ICANON | termios.ECHO | termios.ECHOE | termios.ISIG) attrs[OFLAG] &= ~termios.OPOST # See http://unixwiz.net/techtips/termios-vmin-vtime.html attrs[CC][termios.VMIN] = 0; attrs[CC][termios.VTIME] = 20; termios.tcsetattr(self.fd, termios.TCSANOW, attrs)
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 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 set_curses_term(): termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)
def set_normal_term(): termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
elif key == 'w' : x = 5 elif key == 'd' : x = 2 elif key == 's' : x = 4 elif key == 'a' : x = 3 elif (key == '\x03'): break pub.publish(x) count= count + 1 print(x) imagename = "image" + str(count) + ".jpg" cv2.imwrite(imagename,frame) csv_row.append(imagename) csv_row.append(x) csv_data.append(csv_row) with open('record.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerows(csv_data) csvFile.close() termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
def __exit__(self, type, value, traceback): termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings) # restore sys.stdout sys.stdout.close() sys.stdout = sys.__stdout__
def exit_keycodes_mode(self): log.debug("exit_keycodes_mode") self.filtering = False log.debug("setting mode back to %s", self._old_mode) fcntl.ioctl(self._fd, KDSKBMODE, self._old_mode) termios.tcsetattr(self._fd, termios.TCSANOW, self._old_settings)
def cleanup(self): termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
#!/usr/bin/env python import sys, select, tty, termios import rospy from std_msgs.msg import String if __name__ == '__main__': key_pub = rospy.Publisher('keys', String, queue_size=1) rospy.init_node("keyboard_driver") rate = rospy.Rate(100) # Begin terminos old_attr = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) print "Publishing keystrokes. Press Ctrl-C to exit..." while not rospy.is_shutdown(): if select.select([sys.stdin], [], [], 0)[0] == [sys.stdin]: key_pub.publish(sys.stdin.read(1)) rate.sleep() termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr)
def cleanUp(self): if self.unix: import sys, tty, termios termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)
def tty_restore(self): termios.tcsetattr(self.tty_fd, termios.TCSADRAIN, self.tty_old_settings) self.tty_raw_set = False
def start_connection(play_context, variables, task_uuid): ''' Starts the persistent connection ''' candidate_paths = [C.ANSIBLE_CONNECTION_PATH or os.path.dirname(sys.argv[0])] candidate_paths.extend(os.environ['PATH'].split(os.pathsep)) for dirname in candidate_paths: ansible_connection = os.path.join(dirname, 'ansible-connection') if os.path.isfile(ansible_connection): display.vvvv("Found ansible-connection at path {0}".format(ansible_connection)) break else: raise AnsibleError("Unable to find location of 'ansible-connection'. " "Please set or check the value of ANSIBLE_CONNECTION_PATH") env = os.environ.copy() env.update({ # HACK; most of these paths may change during the controller's lifetime # (eg, due to late dynamic role includes, multi-playbook execution), without a way # to invalidate/update, ansible-connection won't always see the same plugins the controller # can. 'ANSIBLE_BECOME_PLUGINS': become_loader.print_paths(), 'ANSIBLE_CLICONF_PLUGINS': cliconf_loader.print_paths(), 'ANSIBLE_COLLECTIONS_PATH': to_native(os.pathsep.join(AnsibleCollectionConfig.collection_paths)), 'ANSIBLE_CONNECTION_PLUGINS': connection_loader.print_paths(), 'ANSIBLE_HTTPAPI_PLUGINS': httpapi_loader.print_paths(), 'ANSIBLE_NETCONF_PLUGINS': netconf_loader.print_paths(), 'ANSIBLE_TERMINAL_PLUGINS': terminal_loader.print_paths(), }) python = sys.executable master, slave = pty.openpty() p = subprocess.Popen( [python, ansible_connection, to_text(os.getppid()), to_text(task_uuid)], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) os.close(slave) # We need to set the pty into noncanonical mode. This ensures that we # can receive lines longer than 4095 characters (plus newline) without # truncating. old = termios.tcgetattr(master) new = termios.tcgetattr(master) new[3] = new[3] & ~termios.ICANON try: termios.tcsetattr(master, termios.TCSANOW, new) write_to_file_descriptor(master, variables) write_to_file_descriptor(master, play_context.serialize()) (stdout, stderr) = p.communicate() finally: termios.tcsetattr(master, termios.TCSANOW, old) os.close(master) if p.returncode == 0: result = json.loads(to_text(stdout, errors='surrogate_then_replace')) else: try: result = json.loads(to_text(stderr, errors='surrogate_then_replace')) except getattr(json.decoder, 'JSONDecodeError', ValueError): # JSONDecodeError only available on Python 3.5+ result = {'error': to_text(stderr, errors='surrogate_then_replace')} if 'messages' in result: for level, message in result['messages']: if level == 'log': display.display(message, log_only=True) elif level in ('debug', 'v', 'vv', 'vvv', 'vvvv', 'vvvvv', 'vvvvvv'): getattr(display, level)(message, host=play_context.remote_addr) else: if hasattr(display, level): getattr(display, level)(message) else: display.vvvv(message, host=play_context.remote_addr) if 'error' in result: if play_context.verbosity > 2: if result.get('exception'): msg = "The full traceback is:\n" + result['exception'] display.display(msg, color=C.COLOR_ERROR) raise AnsibleError(result['error']) return result['socket_path']
} #### Importing python modules import comware import os import sys import time import termios #### RAW user-input module fd = sys.stdin.fileno() 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) termios.tcsendbreak(fd, 0) #### Notification for Starting print( ('\n' * 5) + "Starting script for deploying IRF-config and software on 5130 switches\n" "\nPlease wait while getting the current versions and settings....") #### Getting Current settings and versions def SwitchInput(): sys.stdout.write("\r%d%%" % 0) sys.stdout.flush() #### Enable logging: flash:/logfile/logfile.log comware.CLI(
import rospy #import service library from std_srvs.srv import Empty #topic to command thrusters_topic = "/g500/thrusters_input" #base velocity for the teleoperation (0.5 m/s) / (0.5rad/s) baseVelocity = 1 #Console input variables to teleop it from the console 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) ##create the publisher pub = rospy.Publisher(thrusters_topic, Float64MultiArray, queue_size=1) rospy.init_node('keyboardCommand') ##wait for benchmark init service #rospy.wait_for_service('/startBench') #start=rospy.ServiceProxy('/startBench', Empty) ##wait for benchmark stop service #rospy.wait_for_service('/stopBench') #stop=rospy.ServiceProxy('/stopBench', Empty)
def __exit__(self, type, value, traceback): termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
def main(): irciot = PyLayerIRCIoT() ircbot = PyLayerIRC() # ircbot.bot_background_start_() # ircbot.bot_redirect_output_('./iotBot.log') irciot.irc_pointer = ircbot.irc_handler irciot.user_pointer = ircbot.user_handler irciot.ldict_file = "./ldict.json" ircbot.irc_server = "irc-iot.nsk.ru" ircbot.irc_port = 6667 #ircbot.irc_server = "chat.freenode.net" #ircbot.irc_port = 6697 #ircbot.irc_ssl = True # Warning: Please, run your own IRC server # don't use public networks for testing!!! ircbot.irc_channel = "#Berdsk" ircbot.irc_debug = True ircbot.irc_define_nick_("TestBot") # ircbot.irc_talk_with_strangers = True # ircbot.irc_ident = True ircbot.start_IRC_() # irciot.irciot_enable_blockchain_(irciot.CONST.tag_mid_ED25519) # irciot.irciot_enable_encryption_(irciot.CONST.tag_ENC_B64_RSA) print("Starting IRC, press any key to exit", "\r") if os.name == "posix": stdin_fd = sys.stdin.fileno() old_term = termios.tcgetattr(stdin_fd) new_attr = old_term[:] new_attr[3] = new_attr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(stdin_fd, termios.TCSANOW, new_attr) old_flag = fcntl.fcntl(stdin_fd, fcntl.F_GETFL) fcntl.fcntl(stdin_fd, fcntl.F_SETFL, old_flag | os.O_NONBLOCK) irc_vuid = "c0" # Bot itself try: while (ircbot.irc_run): (irc_message, irc_wait, irc_vuid) \ = ircbot.irc_check_queue_(ircbot.CONST.irc_queue_input) if (irc_message != ""): print("irc_message=[\033[0;44m{}\033[0m]".format(irc_message)) if (irciot.is_irciot_(irc_message)): irc_json = irciot.irciot_deinencap_(irc_message, irc_vuid) if not irc_json in [None, "", "[]"]: print( "Datumset: [\033[0;41m" + str(irc_json) + "\033[0m]", "\r") sys.stdout.flush() key_a = None if os.name == "nt": if msvcrt.kbhit(): key_a = True elif os.name == "posix": key_a, key_b, key_c = select.select([stdin_fd], [], [], 0.0001) if key_a: print("[Key pressed]") break finally: if os.name == "posix": termios.tcsetattr(stdin_fd, termios.TCSAFLUSH, old_term) fcntl.fcntl(stdin_fd, fcntl.F_SETFL, old_flag) ircbot.irc_run = False ircbot.irc_quit_() print("Stopping IRC, please wait for exit") ircbot.bot_process_kill_timeout_(5) del irciot del ircbot sys.exit()
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 __exit__(self, *args): termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.oldterm) fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags)
def execute(self, context, args, in_opt_format=None, out_opt_format=None): # This function is complex. There are two major variables. First, # are we on Unix or Windows? This is effectively determined by # pty_available, though I suppose some Unixes might not have ptys. # Second, out_opt_format tells us whether we want to stream the # output as lines (out_opt_format is None), or as unbuffered byte chunks # (determined by bytearray/chunked). There is also a special hack # x-filedescriptor/special where we pass along a file descriptor from # the subprocess; this is used in unicode.py to directly read the output. using_pty_out = pty_available and (out_opt_format not in ( None, 'x-unix-pipe-file-object/special')) using_pty_in = pty_available and (in_opt_format is None) and \ context.input_is_first and hasattr(context.input, 'connect') _logger.debug("using pty in: %s out: %s", using_pty_in, using_pty_out) # TODO - we need to rework things so that we allocate only one pty per pipeline. # In the very common case of exactly one command, this doesn't matter, but # allocating two ptys will probably bite us in odd ways if someone does create # a pipeline. Maybe have a context.request_pty() function? if using_pty_in or using_pty_out: # We create a pseudo-terminal to ensure that the subprocess is line-buffered. # Yes, this is gross, but as far as I know there is no other way to # control the buffering used by subprocesses. (master_fd, slave_fd) = pty.openpty() # Set the terminal to not do any processing; if you change this, you'll also # need to update unicode.py most likely. attrs = termios.tcgetattr(master_fd) attrs[1] = attrs[1] & (~termios.OPOST) termios.tcsetattr(master_fd, termios.TCSANOW, attrs) _logger.debug("allocated pty fds %d %d", master_fd, slave_fd) if using_pty_out: stdout_target = slave_fd else: stdout_target = subprocess.PIPE if context.input is None: stdin_target = None if using_pty_in: stdin_target = slave_fd elif in_opt_format == 'x-unix-pipe-file-object/special': stdin_target = iter(context.input).next() else: stdin_target = subprocess.PIPE _logger.debug("using stdin target: %r", stdin_target) context.attribs['master_fd'] = master_fd else: _logger.debug( "no pty available or non-chunked output, not allocating fds") (master_fd, slave_fd) = (None, None) stdout_target = subprocess.PIPE if context.input is None: stdin_target = None elif in_opt_format == 'x-unix-pipe-file-object/special': stdin_target = iter(context.input).next() else: stdin_target = subprocess.PIPE _logger.debug("using stdin target: %r", stdin_target) subproc_args = { 'bufsize': 0, 'stdin': stdin_target, 'stdout': stdout_target, 'stderr': subprocess.STDOUT, 'cwd': context.cwd } fs_encoding = sys.getfilesystemencoding() stdin_encoding = sys.stdin.encoding _logger.debug("recoding path to %r, args to %r", fs_encoding, stdin_encoding) # We need to encode_sentence arguments to the system encoding because subprocess.py won't do it for us. if fs_encoding is not None: args[0] = args[0].encode(fs_encoding) if stdin_encoding is not None: args[1:] = map(lambda x: x.encode(stdin_encoding), args[1:]) if is_windows(): subproc_args['universal_newlines'] = True startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW import win32con startupinfo.wShowWindow = win32con.SW_HIDE elif is_unix(): subproc_args['close_fds'] = True # Support freedesktop.org startup notification # http://standards.freedesktop.org/startup-notification-spec/startup-notification-latest.txt if context.gtk_event_time: env = dict(os.environ) env['DESKTOP_STARTUP_ID'] = 'hotwire%d_TIME%d' % ( os.getpid(), context.gtk_event_time, ) subproc_args['env'] = env def preexec(): os.setsid() if using_pty_out and hasattr(termios, 'TIOCSCTTY'): # Set our controlling TTY fcntl.ioctl(1, termios.TIOCSCTTY, '') # We ignore SIGHUP by default, because some broken programs expect that the lifetime # of subcommands is tied to an open window, instead of until when the toplevel # process exits. signal.signal(signal.SIGHUP, signal.SIG_IGN) subproc_args['preexec_fn'] = preexec else: assert (False) subproc = subprocess.Popen(args, **subproc_args) if not subproc.pid: if master_fd is not None: os.close(master_fd) if slave_fd is not None: os.close(slave_fd) raise ValueError('Failed to execute %s' % (args[0], )) context.attribs['pid'] = subproc.pid if using_pty_in or using_pty_out: os.close(slave_fd) context.status_notify('pid %d' % (context.attribs['pid'], )) if in_opt_format == 'x-unix-pipe-file-object/special': stdin_target.close() # If we were passed a file descriptor from another SysBuiltin, close it here; # it's now owned by the child. elif context.input: if using_pty_in: stdin_stream = BareFdStreamWriter(master_fd) else: stdin_stream = subproc.stdin # FIXME hack - need to rework input streaming if context.input_is_first and hasattr(context.input, 'connect'): context.attribs['input_connected'] = True context.input.connect(self.__on_input, stdin_stream) else: MiniThreadPool.getInstance().run(self.__inputwriter, args=(context.input, stdin_stream)) if using_pty_out: stdout_read = None stdout_fd = master_fd else: stdout_read = subproc.stdout stdout_fd = subproc.stdout.fileno() if out_opt_format is None: for line in SysBuiltin.__unbuffered_readlines(stdout_read): yield line elif out_opt_format == 'bytearray/chunked': try: for buf in SysBuiltin.__unbuffered_read_pipe( stream=stdout_read, fd=stdout_fd): yield buf except OSError, e: pass
def set_normal_term(self): """ Resets to normal terminal. """ termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def parsedemo(s): """ Helper to write demo files, based on minimum change from their Matlab format. The string contains - help text which is left justified and displayed directly to the screen - indented text is interpretted as a command, executed, and the output sent to screen The argument is Matlab code as per the demo files rtXXdemo. @note: Requires some minor changes to the demo file. @type s: string @param s: Demo string. """ rstrip = re.compile(r'''\s*%.*$''') lines = s.split('\n') name = __file__ print(name) print(len(name) * '=') if has_termios: fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ECHO # lflags try: if has_termios: termios.tcsetattr(fd, termios.TCSADRAIN, new) text = '' for line in lines: if len(line) == 0: print() elif line[0] == '#': ## help text found, add it to the string text += line[1:].lstrip() + '\n' # a blank line means paragraph break if len(line) == 1 and text: print(textwrap.fill(text, fix_sentence_endings=True)) text = '' print() else: ## command encountered # flush the remaining help text if text: print(textwrap.fill(text, fix_sentence_endings=True)) text = '' cmd = line.strip() # special case, pause prompts the user to continue if cmd.startswith('pause'): # prompt for continuation sys.stderr.write('more? ') input() # remove the prompt from the screen sys.stderr.write('\r \r') continue print() # show the command we are about to execute print('>>>', cmd) # if it involves an assignment then we use exec else use eval. # we mimic the matlab behaviour in which a trailing semicolon inhibits # display of the result try: if cmd.startswith('from'): exec(cmd) elif '=' in cmd: e = cmd.split('=') exec(rstrip.sub('', cmd)) if cmd[-1] != ';': print(eval(e[0])) else: result = eval(cmd.rstrip(';')) if cmd[-1] != ';': print(result) except: print("Error at line <%s>" % cmd) traceback.print_exc() sys.exit(1) finally: if has_termios: termios.tcsetattr(fd, termios.TCSADRAIN, old)
def streamSwingTrial(): """Runs a swing trial event and computes important bat metrics Returns the bat metrics in an array """ k = KemanImu() imu = initialize() print "5 seconds to Calibrate. Please hold Calibration Position:" tm.sleep(5.5) # Wait for calibration position e_initial = k.calibrate(imu) # Obtain four initial euler parameters #e_initial = normalizeEulerParameters(e_initial) #Normalize initialTime = tm.time() # Time # Initialize Storage Vectors acceleration = k.readAcceleration(imu) angularVelocity = k.readAngularVelocity(imu) xinertialAccelerationVector = [0] yinertialAccelerationVector = [0] zinertialAccelerationVector = [0] velocityMagnitudeVector = [0] xAccelerationVector = [acceleration[0]] yAccelerationVector = [acceleration[1]] zAccelerationVector = [acceleration[2]] xAngularVelocity = [angularVelocity[0]] yAngularVelocity = [angularVelocity[1]] zAngularVelocity = [angularVelocity[2]] aimAngleVector = [0] rollVector = [0] rotationMatrices = [k.computeDirectionCosineMatrix(e_initial)] elevationAngles = [0] timeVectors = [0] sampleTimes = [0] calibration_angles = [0] # Initialize useful computation variables previousEpochTime = initialTime # t0 previousElapsedSampleTime = 0 currentElapsedSampleTime = 0 previousEulerParameters = e_initial index = 0 try: tty.setcbreak(sys.stdin.fileno()) # Loop for 10 seconds input( 'press 1 to stop program\n press 2 to kill recording\n press 3 to start recording \n press 4 to record at 10 deg' ) isSwinging = False while (keyboard() != 'stop'): while (keyboard() != 'kill'): #read callibration angles tm.sleep(.5) if ((keyboard() != 'kill') and (keyboard() != 'stop')): calibration_angles.append(keyboard()) # Read Angular Velocity and Acceleration currentAngularVelocity = k.readAngularVelocity(imu) currentAcceleration = k.readAcceleration(imu) xAccelerationVector.append(currentAcceleration[0]) yAccelerationVector.append(currentAcceleration[1]) zAccelerationVector.append(currentAcceleration[2]) xAngularVelocity.append(currentAngularVelocity[0]) yAngularVelocity.append(currentAngularVelocity[1]) zAngularVelocity.append(currentAngularVelocity[2]) currentEpochTime = tm.time() currentElapsedSampleTime = currentEpochTime - previousEpochTime sampleTimes.append(currentElapsedSampleTime) timeVectors.append( previousElapsedSampleTime + currentElapsedSampleTime ) # Time History TODO: CHANGE NAME TO AVOID CONFUSION timeVector = [0, currentElapsedSampleTime] # TODO:Do we have to normalize the quaternion? # TODO:Can we use this same solver or do we have to switch # Solve for current rotation matrix currentEulerParameters = k.computeEulerParameters( previousEulerParameters, timeVector, currentAngularVelocity) eulerParametersNormalized = currentEulerParameters #eulerPrametersNoramlized = normalizeEulerParameters(currentEulerParameters) # Compute Direction Cosine Matrix directionMatrix = k.computeDirectionCosineMatrix( eulerParametersNormalized) rotationMatrices.append(directionMatrix) #print "Direction Cosine Matrix:", directionMatrix[0] # Get Inertial Acceleration snd Velocity xinertialAcceleration, yinertialAcceleration, zinertialAcceleration = k.computeInertialAcceleration( imu, directionMatrix) xinertialAccelerationVector.append(xinertialAcceleration) yinertialAccelerationVector.append(yinertialAcceleration) zinertialAccelerationVector.append(zinertialAcceleration) # Stop collecting data once acceleration has reached zero again. previousEulerParameters = currentEulerParameters previousEpochTime = currentEpochTime previousElapsedSampleTime += currentElapsedSampleTime # move to next step #Calculate Yaw, pitch and roll elevationAngle = asin(directionMatrix[0][2]) * 57.3 aimAngle = atan( directionMatrix[0][1] / directionMatrix[0][0]) * 57.3 #roll = currentEulerParameters[3]**2 - currentEulerParameters[1]**2 \ # - currentEulerParameters[2]**2 - currentEulerParameters[3]**2 #roll = acos(roll) * 57.3 roll = atan( directionMatrix[1][2] / directionMatrix[2][2]) * 57.3 elevationAngles.append(elevationAngle) aimAngleVector.append(aimAngle) rollVector.append(roll) isSwinging = True # Compute Velocity if (isSwinging): xinertialVelocity = k.computeVelocityHistory( xinertialAccelerationVector, sampleTimes) yinertialVelocity = k.computeVelocityHistory( yinertialAccelerationVector, sampleTimes) zinertialVelocity = k.computeVelocityHistory( zinertialAccelerationVector, sampleTimes) xpositionVector = k.computePosition(xinertialVelocity, sampleTimes) ypositionVector = k.computePosition(yinertialVelocity, sampleTimes) zpositionVector = k.computePosition(zinertialVelocity, sampleTimes) #TODO: FIX THIS velocityMagnitude = k.computeVelocityMagnitude( xinertialVelocity, yinertialVelocity, zinertialVelocity) velocityMagnitudeVector.append(velocityMagnitude) sweetSpotVelocityVector = k.computeSweetSpotVelocity( [xinertialVelocity, yinertialVelocity, zinertialVelocity], [xAngularVelocity, yAngularVelocity, zAngularVelocity]) roundEntries(yAccelerationVector) roundEntries(zAccelerationVector) roundEntries(xAngularVelocity) roundEntries(yAngularVelocity) roundEntries(zAngularVelocity) roundEntries(elevationAngles) roundEntries(timeVectors) roundEntries(xinertialVelocity) roundEntries(yinertialVelocity) roundEntries(zinertialVelocity) roundEntries(xinertialAccelerationVector) roundEntries(yinertialAccelerationVector) roundEntries(zinertialAccelerationVector) roundEntries(aimAngleVector) roundEntries(rollVector) roundEntries(sweetSpotVelocityVector) roundEntries(velocityMagnitude) roundEntries(xpositionVector) roundEntries(ypositionVector) roundEntries(zpositionVector) payload = { "accelx": xinertialAccelerationVector, "accely": yinertialAccelerationVector, "accelz": yinertialAccelerationVector } r = requests.post( 'https://obscure-headland-45385.herokuapp.com/hips', json=payload) isSwinging = False # s.connect(('192.168.1.41', port)) # transmitString = listToString(xAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(yAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(zAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(xAngularVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(yAngularVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(zAngularVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(elevationAngles) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(timeVectors) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(xinertialVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(yinertialVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(zinertialVelocity) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(xinertialAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(yinertialAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(zinertialAccelerationVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(aimAngleVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(rollVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(sweetSpotVelocityVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(velocityMagnitude) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(xpositionVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(ypositionVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(zpositionVector) # transmitString = transmitString + '!' # transmitString = transmitString + listToString(calibration_angles) # # sendData(transmitString) s.close() finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
def posix_shell(self): """ Use paramiko channel connect server interactive. 使用paramiko模块的channel,连接后端,进入交互式 """ log_file_f, log_time_f, log = self.get_log() 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 if self.vim_flag: self.vim_data += x 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 #sys.stdout.write(x) #sys.stdout.flush() now_timestamp = time.time() 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() if input_mode and not self.is_output(x): data += x except socket.timeout: pass if sys.stdin in r: x = os.read(sys.stdin.fileno(), 4096) input_mode = True if str(x) in ['\r', '\n', '\r\n']: if self.vim_flag: match = self.ps1_pattern.search(self.vim_data) if match: self.vim_flag = False data = self.deal_command(data)[0:200] if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() else: data = self.deal_command(data)[0:200] if len(data) > 0: 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() log.is_finished = True log.end_time = datetime.datetime.now() log.save()
KEY_PRESSED_RIGHT = True if ch == "W": KEY_PRESSED_UP = True if ch == "A": KEY_PRESSED_LEFT = True if ch == "D": KEY_PRESSED_RIGHT = True if ch == " ": KEY_PRESSED_SPACE = True if ch == "q" or ch == "Q": quit() if ch == "F" or ch == "f": KEY_PRESSED_FIRE = True # if this sentence in the game over, graph not right termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) if KEY_PRESSED_UP == True: manda.moveup() if KEY_PRESSED_LEFT == True: manda.moveleft() if KEY_PRESSED_SPACE == True: if shield_counter == 300: shield_active = 1 if KEY_PRESSED_FIRE == True: fight.shoot_goli(manda, counter) if refil == 1 and KEY_PRESSED_SPACE == True: shield_counter -= 4
def mypublisher(): rospy.init_node('publisher_2', anonymous=True) rate = rospy.Rate(10) # 10hz my_msg.name=['base_to_oratation','base_to_left_front_wheel','base_to_left_back_wheel','base_to_right_front_wheel','base_to_right_back_wheel', 'base_to_right_arm_1', 'base_to_left_arm_1', 'joint_of_left_arm', 'joint_of_right_arm'] my_msg.position = [0,0,0,0,0,0,0,0,0] i=0#the position of all four wheels p=0#position of base jr1=0#position of base_to_right_arm_1 jr2=0#position of joint_of_right_arm jl1=0#position of base_to_left_arm_1 jl2=0#position of joint_of_left_arm i_1=0 while not rospy.is_shutdown(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) old_settings[3] = old_settings[3] & ~termios.ICANON & ~termios.ECHO try : tty.setraw( fd ) ch = sys.stdin.read( 1 ) finally : termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) my_msg.header.seq = i_1 my_msg.header.stamp = rospy.Time.now() #my_msg.position = [i*0.0314,0,0,0,0,0,0,0] ##my_msg.velocity = [i,i,i,i,i,i,i,i] if ch == 'w': i=i+1 p=p+1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 's': i=i-1 p=p-1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'k': jr1=jr1+1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'l': jr1=jr1-1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'h': jl1=jl1+1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'j': jl1=jl1-1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'y': jl2=jl2+1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'u': jl2=jl2-1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'o': jr2=jr2+1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'p': jr2=jr2-1 my_msg.position = [p*0.3*pi,i*pi/2,i*pi/2,i*pi/2,i*pi/2,jr1*pi/20,jl1*pi/20,jl2*pi/20,jr2*pi/20] elif ch == 'q': exit() i_1 = i_1 + 1 rospy.loginfo(my_msg) pub.publish(my_msg) rate.sleep() stop_robot();
def __exit__(self, *unused): if self.attrs is not None: termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, self.attrs)
def set_normal_term(self): ''' Resets to normal terminal. On Windows this is a no-op. ''' termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def deinit_tty(): termios.tcsetattr(Editor.sdev, termios.TCSANOW, Editor.org_termios)
def getKey(): tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) key = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) return key
def __exit__(self, exc_type, exc_value, traceback): termios.tcsetattr(sys.stdin.fileno(), termios.TCSAFLUSH, self.old_attr) fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFD, self.old_flags) os.close(self.master) os.waitpid(self.pid, 0)
def restore_terminal(self): fd = sys.stdin.fileno() if self.oldTerm: termios.tcsetattr(fd, termios.TCSAFLUSH, self.oldTerm) if self.oldFlags: fcntl.fcntl(fd, fcntl.F_SETFL, self.oldFlags)
def disable_echo(fd): old = termios.tcgetattr(fd) new = cfmakeraw(old) flags = (termios.TCSAFLUSH | getattr(termios, 'TCSASOFT', 0)) termios.tcsetattr(fd, flags, new)