Module remotePythonConsole
[hide private]
[frames] | no frames]

Source Code for Module remotePythonConsole

 1  #remotePythonConsole.py 
 2  #A part of NonVisual Desktop Access (NVDA) 
 3  #This file is covered by the GNU General Public License. 
 4  #See the file COPYING for more details. 
 5  #Copyright (C) 2011 NV Access Inc 
 6   
 7  """Provides an interactive Python console run inside NVDA which can be accessed via TCP. 
 8  To use, call L{initialize} to start the server. 
 9  Then, connect to it using TCP port L{PORT}. 
10  The server will only handle one connection at a time. 
11  """ 
12   
13  import threading 
14  import SocketServer 
15  import wx 
16  import pythonConsole 
17  from logHandler import log 
18   
19  #: The TCP port on which the server will run. 
20  #: @type: int 
21  PORT = 6832 
22   
23  server = None 
24   
25 -class RequestHandler(SocketServer.StreamRequestHandler):
26
27 - def setPrompt(self, prompt):
28 if not self._keepRunning: 29 # We're about to exit, so don't output the prompt. 30 return 31 self.wfile.write(prompt + " ")
32
33 - def exit(self):
34 self._keepRunning = False
35
36 - def execute(self, line):
37 self.console.push(line) 38 # Notify handle() that the line has finished executing. 39 self._execDoneEvt.set()
40
41 - def handle(self):
42 self._keepRunning = True 43 44 try: 45 self.wfile.write("NVDA Remote Python Console\n") 46 self.console = pythonConsole.PythonConsole(outputFunc=self.wfile.write, setPromptFunc=self.setPrompt, exitFunc=self.exit) 47 self.console.namespace.update({ 48 "snap": self.console.updateNamespaceSnapshotVars, 49 "rmSnap": self.console.removeNamespaceSnapshotVars, 50 }) 51 52 self._execDoneEvt = threading.Event() 53 while self._keepRunning: 54 line = self.rfile.readline() 55 if not line: 56 break 57 line = line.rstrip("\r\n") 58 # Execute in the main thread. 59 wx.CallAfter(self.execute, line) 60 # Wait until the line has finished executing before retrieving the next. 61 self._execDoneEvt.wait() 62 self._execDoneEvt.clear() 63 64 except: 65 log.exception("Error handling remote Python console request") 66 finally: 67 # Clean up the console. 68 self.console = None
69
70 -def initialize():
71 global server 72 server = SocketServer.TCPServer(("", PORT), RequestHandler) 73 server.daemon_threads = True 74 thread = threading.Thread(target=server.serve_forever) 75 thread.daemon = True 76 thread.start()
77
78 -def terminate():
79 global server 80 server.shutdown() 81 server = None
82