def run(self): """Handle requests""" while 1: # Get most recent request request = None while 1: try: request = self.queue.get(True, 0.01) except Queue.Empty: break if request is None: if time.time() - self.tlast > TIMEOUT: sys.exit('Program timed out') continue self.tlast = time.time() try: method = getattr(self.plugin, request['method']) args = request.get('args', []) kwargs = request.get('kwargs', {}) request['result'] = method(*args, **kwargs) except Exception as e: request['error'] = str(e) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._client_port)) write_packet(sock, request) sock.close()
def __init__(self, client_port, plugin_name): mod_name = plugin_name + '_plugin' mod = __import__('spyderlib.utils.introspection.' + mod_name, fromlist=[mod_name]) cls = getattr(mod, '%sPlugin' % plugin_name.capitalize()) plugin = cls() plugin.load_plugin() self.tlast = time.time() self.plugin = plugin self._client_port = int(client_port) sock, self.server_port = connect_to_port() sock.listen(2) atexit.register(sock.close) self._server_sock = sock self.queue = Queue.Queue() self._listener = threading.Thread(target=self.listen) self._listener.setDaemon(True) self._listener.start() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._client_port)) write_packet(sock, self.server_port) sock.close()
def send(self, request): """Send a request to the plugin. """ if not self._initialized: return sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self.client_port)) request['plugin_name'] = self.plugin_name write_packet(sock, request) sock.close()
def run(self): """Start notification thread""" while True: if self.notify_socket is None: continue output = None try: try: cdict = read_packet(self.notify_socket) except: # This except statement is intended to handle a struct.error # (but when writing 'except struct.error', it doesn't work) # Note: struct.error is raised when the communication has # been interrupted and the received data is not a string # of length 8 as required by struct.unpack (see read_packet) break if cdict is None: # Another notification thread has just terminated and # then wrote 'None' in the notification socket # (see the 'finally' statement below) continue if not isinstance(cdict, dict): raise TypeError("Invalid data type: %r" % cdict) command = cdict['command'] data = cdict.get('data') if command == 'pdb_step': fname, lineno = data self.emit(SIGNAL('pdb(QString,int)'), fname, lineno) self.emit(SIGNAL('refresh_namespace_browser()')) elif command == 'refresh': self.emit(SIGNAL('refresh_namespace_browser()')) elif command == 'remote_view': self.sig_process_remote_view.emit(data) elif command == 'ipykernel': self.emit(SIGNAL('new_ipython_kernel(QString)'), data) elif command == 'open_file': fname, lineno = data self.emit(SIGNAL('open_file(QString,int)'), fname, lineno) else: raise RuntimeError('Unsupported command: %r' % command) if DEBUG_INTROSPECTION: logging.debug("received command: %r" % command) except: log_last_error(LOG_FILENAME, "notification thread") finally: try: write_packet(self.notify_socket, output) except: # The only reason why it should fail is that Spyder is # closing while this thread is still alive break
def run(self): """Start notification thread""" while True: if self.notify_socket is None: continue output = None try: try: cdict = read_packet(self.notify_socket) except: # This except statement is intended to handle a struct.error # (but when writing 'except struct.error', it doesn't work) # Note: struct.error is raised when the communication has # been interrupted and the received data is not a string # of length 8 as required by struct.unpack (see read_packet) break if cdict is None: # Another notification thread has just terminated and # then wrote 'None' in the notification socket # (see the 'finally' statement below) continue if not isinstance(cdict, dict): raise TypeError("Invalid data type: %r" % cdict) command = cdict['command'] data = cdict.get('data') if command == 'pdb_step': fname, lineno = data self.sig_pdb.emit(fname, lineno) self.refresh_namespace_browser.emit() elif command == 'refresh': self.refresh_namespace_browser.emit() elif command == 'remote_view': self.sig_process_remote_view.emit(data) elif command == 'ipykernel': self.new_ipython_kernel.emit(data) elif command == 'open_file': fname, lineno = data self.open_file.emit(fname, lineno) else: raise RuntimeError('Unsupported command: %r' % command) if DEBUG_INTROSPECTION: logging.debug("received command: %r" % command) except: log_last_error(LOG_FILENAME, "notification thread") finally: try: write_packet(self.notify_socket, output) except: # The only reason why it should fail is that Spyder is # closing while this thread is still alive break
def quit_monitor(self): if self.introspection_socket is not None: try: write_packet(self.introspection_socket, "thread.exit()") except socket.error: pass
def run(self): self.ipython_shell = None while True: output = pickle.dumps(None, PICKLE_HIGHEST_PROTOCOL) glbs = self.mglobals() try: if DEBUG_MONITOR: logging.debug("****** Introspection request /Begin ******") command = PACKET_NOT_RECEIVED try: timeout = self.timeout if self.auto_refresh else None command = read_packet(self.i_request, timeout=timeout) if command is None: continue timed_out = False except socket.timeout: timed_out = True except struct.error: # This should mean that Spyder GUI has crashed if DEBUG_MONITOR: logging.debug("struct.error -> quitting monitor") break if timed_out: if DEBUG_MONITOR: logging.debug( "connection timed out -> updating remote view") self.update_remote_view() if DEBUG_MONITOR: logging.debug( "****** Introspection request /End ******") continue if DEBUG_MONITOR: logging.debug("command: %r" % command) lcls = self.mlocals() result = eval(command, glbs, lcls) if DEBUG_MONITOR: logging.debug(" result: %r" % result) if self.pdb_obj is None: lcls["_"] = result # old com implementation: (see solution (1) in Issue 434) output = pickle.dumps(result, PICKLE_HIGHEST_PROTOCOL) # # new com implementation: (see solution (2) in Issue 434) # output = pickle.dumps((command, result), # PICKLE_HIGHEST_PROTOCOL) except SystemExit: break except: if DEBUG_MONITOR: logging.debug("error!") log_last_error(LOG_FILENAME, command) finally: try: if DEBUG_MONITOR: logging.debug("updating remote view") if self.refresh_after_eval: self.update_remote_view() self.refresh_after_eval = False if DEBUG_MONITOR: logging.debug("sending result") logging.debug( "****** Introspection request /End ******") if command is not PACKET_NOT_RECEIVED: if write_packet is None: # This may happen during interpreter shutdown break else: write_packet(self.i_request, output, already_pickled=True) except AttributeError as error: if "'NoneType' object has no attribute" in str(error): # This may happen during interpreter shutdown break else: raise except TypeError as error: if "'NoneType' object is not subscriptable" in str(error): # This may happen during interpreter shutdown break else: raise self.i_request.close() self.n_request.close()
def __init__(self, host, introspection_port, notification_port, shell_id, timeout, auto_refresh): threading.Thread.__init__(self) self.setDaemon(True) self.ipykernel = None self.ipython_shell = None self.pdb_obj = None self.timeout = None self.set_timeout(timeout) self.auto_refresh = auto_refresh self.refresh_after_eval = False self.remote_view_settings = None self.inputhook_flag = False self.first_inputhook_call = True # To grab the IPython internal namespace self.ip = None # Connecting to introspection server self.i_request = socket.socket(socket.AF_INET) self.i_request.connect((host, introspection_port)) write_packet(self.i_request, shell_id) # Connecting to notification server self.n_request = socket.socket(socket.AF_INET) self.n_request.connect((host, notification_port)) write_packet(self.n_request, shell_id) self._mlocals = { "refresh": self.enable_refresh_after_eval, "setlocal": self.setlocal, "is_array": self.is_array, "is_image": self.is_image, "get_globals_keys": self.get_globals_keys, "getmodcomplist": self.getmodcomplist, "getcdlistdir": _getcdlistdir, "getcwd": self.getcwd, "setcwd": self.setcwd, "getsyspath": self.getsyspath, "getenv": self.getenv, "setenv": self.setenv, "isdefined": self.isdefined, "thread": _thread, "toggle_inputhook_flag": self.toggle_inputhook_flag, "set_monitor_timeout": self.set_timeout, "set_monitor_auto_refresh": self.set_auto_refresh, "set_remote_view_settings": self.set_remote_view_settings, "set_spyder_breakpoints": self.set_spyder_breakpoints, "__get_dir__": self.get_dir, "__iscallable__": self.iscallable, "__get_arglist__": self.get_arglist, "__get__doc____": self.get__doc__, "__get_doc__": self.get_doc, "__get_source__": self.get_source, "__get_global__": self.getglobal, "__set_global__": self.setglobal, "__del_global__": self.delglobal, "__copy_global__": self.copyglobal, "__save_globals__": self.saveglobals, "__load_globals__": self.loadglobals, "_": None } self._mglobals = None
def run(self): self.ipython_shell = None while True: output = pickle.dumps(None, PICKLE_HIGHEST_PROTOCOL) glbs = self.mglobals() try: if DEBUG_MONITOR: logging.debug("****** Introspection request /Begin ******") command = PACKET_NOT_RECEIVED try: timeout = self.timeout if self.auto_refresh else None command = read_packet(self.i_request, timeout=timeout) if command is None: continue timed_out = False except socket.timeout: timed_out = True except struct.error: # This should mean that Spyder GUI has crashed if DEBUG_MONITOR: logging.debug("struct.error -> quitting monitor") break if timed_out: if DEBUG_MONITOR: logging.debug("connection timed out -> updating remote view") self.update_remote_view() if DEBUG_MONITOR: logging.debug("****** Introspection request /End ******") continue if DEBUG_MONITOR: logging.debug("command: %r" % command) lcls = self.mlocals() result = eval(command, glbs, lcls) if DEBUG_MONITOR: logging.debug(" result: %r" % result) if self.pdb_obj is None: lcls["_"] = result # old com implementation: (see solution (1) in Issue 434) output = pickle.dumps(result, PICKLE_HIGHEST_PROTOCOL) # # new com implementation: (see solution (2) in Issue 434) # output = pickle.dumps((command, result), # PICKLE_HIGHEST_PROTOCOL) except SystemExit: break except: if DEBUG_MONITOR: logging.debug("error!") log_last_error(LOG_FILENAME, command) finally: try: if DEBUG_MONITOR: logging.debug("updating remote view") if self.refresh_after_eval: self.update_remote_view() self.refresh_after_eval = False if DEBUG_MONITOR: logging.debug("sending result") logging.debug("****** Introspection request /End ******") if command is not PACKET_NOT_RECEIVED: if write_packet is None: # This may happen during interpreter shutdown break else: write_packet(self.i_request, output, already_pickled=True) except AttributeError as error: if "'NoneType' object has no attribute" in str(error): # This may happen during interpreter shutdown break else: raise except TypeError as error: if "'NoneType' object is not subscriptable" in str(error): # This may happen during interpreter shutdown break else: raise self.i_request.close() self.n_request.close()
def __init__(self, host, introspection_port, notification_port, shell_id, timeout, auto_refresh): threading.Thread.__init__(self) self.setDaemon(True) self.ipykernel = None self.ipython_shell = None self.pdb_obj = None self.timeout = None self.set_timeout(timeout) self.auto_refresh = auto_refresh self.refresh_after_eval = False self.remote_view_settings = None self.inputhook_flag = False self.first_inputhook_call = True # To grab the IPython internal namespace self.ip = None # Connecting to introspection server self.i_request = socket.socket(socket.AF_INET) self.i_request.connect((host, introspection_port)) write_packet(self.i_request, shell_id) # Connecting to notification server self.n_request = socket.socket(socket.AF_INET) self.n_request.connect((host, notification_port)) write_packet(self.n_request, shell_id) self._mlocals = { "refresh": self.enable_refresh_after_eval, "setlocal": self.setlocal, "is_array": self.is_array, "is_image": self.is_image, "get_globals_keys": self.get_globals_keys, "getmodcomplist": self.getmodcomplist, "getcdlistdir": _getcdlistdir, "getcwd": self.getcwd, "setcwd": self.setcwd, "getsyspath": self.getsyspath, "getenv": self.getenv, "setenv": self.setenv, "isdefined": self.isdefined, "thread": _thread, "toggle_inputhook_flag": self.toggle_inputhook_flag, "set_monitor_timeout": self.set_timeout, "set_monitor_auto_refresh": self.set_auto_refresh, "set_remote_view_settings": self.set_remote_view_settings, "set_spyder_breakpoints": self.set_spyder_breakpoints, "__get_dir__": self.get_dir, "__iscallable__": self.iscallable, "__get_arglist__": self.get_arglist, "__get__doc____": self.get__doc__, "__get_doc__": self.get_doc, "__get_source__": self.get_source, "__get_global__": self.getglobal, "__set_global__": self.setglobal, "__del_global__": self.delglobal, "__copy_global__": self.copyglobal, "__save_globals__": self.saveglobals, "__load_globals__": self.loadglobals, "_": None, } self._mglobals = None
def run(self): """Start notification thread""" while True: if self.notify_socket is None: continue output = None try: try: cdict = read_packet(self.notify_socket) except: # This except statement is intended to handle a struct.error # (but when writing 'except struct.error', it doesn't work) # Note: struct.error is raised when the communication has # been interrupted and the received data is not a string # of length 8 as required by struct.unpack (see read_packet) break if cdict is None: # Another notification thread has just terminated and # then wrote 'None' in the notification socket # (see the 'finally' statement below) continue if not isinstance(cdict, dict): raise TypeError("Invalid data type: %r" % cdict) command = cdict['command'] data = cdict.get('data') if command == 'pdb_step': fname, lineno = data self.emit(SIGNAL('pdb(QString,int)'), fname, lineno) self.emit(SIGNAL('refresh_namespace_browser()')) elif command == 'refresh': self.emit(SIGNAL('refresh_namespace_browser()')) elif command == 'remote_view': self.sig_process_remote_view.emit(data) elif command == 'ipykernel': self.emit(SIGNAL('new_ipython_kernel(QString)'), data) elif command == 'open_file': fname, lineno = data self.emit(SIGNAL('open_file(QString,int)'), fname, lineno) elif command == 'layout': #print('2.3.4 NotificationThread layout') sbml = data if sbml != '~::empty::~': #print('2.3.4 NotificationThread emit layout signal') self.layout.emit(sbml) else: #print('2.3.4 NotificationThread get sbml') if hasattr(self, 'network_viewer_sbml_hook'): output = self.network_viewer_sbml_hook() #print('output = {}'.format(output)) #else: #print('no attr network_viewer_sbml_hook') else: raise RuntimeError('Unsupported command: %r' % command) if DEBUG_INTROSPECTION: logging.debug("received command: %r" % command) except: log_last_error(LOG_FILENAME, "notification thread") finally: try: write_packet(self.notify_socket, output) except: # The only reason why it should fail is that Spyder is # closing while this thread is still alive break
def run(self): #print('run') """Start notification thread""" while True: #print('SBNWNotificationThread while True') # add layout signal if it doesn't already exist #if not hasattr(self, 'layout'): if self.notify_socket is None: continue output = None try: try: cdict = read_packet(self.notify_socket) except: # This except statement is intended to handle a struct.error # (but when writing 'except struct.error', it doesn't work) # Note: struct.error is raised when the communication has # been interrupted and the received data is not a string # of length 8 as required by struct.unpack (see read_packet) break if cdict is None: # Another notification thread has just terminated and # then wrote 'None' in the notification socket # (see the 'finally' statement below) continue if not isinstance(cdict, dict): raise TypeError("Invalid data type: %r" % cdict) command = cdict['command'] data = cdict.get('data') if command == 'pdb_step': fname, lineno = data self.sig_pdb.emit(fname, lineno) self.refresh_namespace_browser.emit() elif command == 'refresh': self.refresh_namespace_browser.emit() elif command == 'remote_view': self.sig_process_remote_view.emit(data) elif command == 'ipykernel': self.new_ipython_kernel.emit(data) elif command == 'open_file': fname, lineno = data self.open_file.emit(fname, lineno) elif command == 'layout': print('SBNWNotificationThread layout') sbml = data if sbml != '~::empty::~': print('SBNWNotificationThread emit layout signal') self.layout.emit(sbml) else: print('SBNWNotificationThread get sbml') if hasattr(self, 'network_viewer_sbml_hook'): output = self.network_viewer_sbml_hook() print('output = {}'.format(output)) else: print('no attr network_viewer_sbml_hook') else: raise RuntimeError('Unsupported command: %r' % command) if DEBUG_INTROSPECTION: logging.debug("received command: %r" % command) except: log_last_error(LOG_FILENAME, "notification thread") finally: try: write_packet(self.notify_socket, output) except: # The only reason why it should fail is that Spyder is # closing while this thread is still alive break