Package turbogears :: Package toolbox :: Module shell

Source Code for Module turbogears.toolbox.shell

  1  import logging 
  2  import sys 
  3  import StringIO 
  4   
  5  import turbogears 
  6  import pkg_resources 
  7  from turbogears import controllers, expose 
  8  from code import InteractiveConsole 
  9   
 10   
 11  log = logging.getLogger('turbogears.toolbox') 
12 13 14 -class WebConsole(controllers.RootController):
15 """Web based Python interpreter""" 16 17 __label__ = 'WebConsole' 18 19 icon = "/tg_static/images/shell.png" 20
21 - def __init__(self, width=80):
22 self.console = None 23 24 try: 25 sys.ps1 26 except AttributeError: 27 sys.ps1 = '>>> ' 28 try: 29 sys.ps2 30 except AttributeError: 31 sys.ps2 = '... '
32 33 @expose()
34 - def process_request(self, line):
35 more, output = self._process_request(line) 36 return dict(more=more, output=output)
37 38 @expose()
39 - def process_multiline_request(self, block):
40 outlines = [] 41 42 lines = [line for line in block.split('\n')] 43 44 for line in lines: 45 more, output = self._process_request(line) 46 47 if output[-1] == '\n': # we'll handle the newlines later. 48 output = output[:-1] 49 50 outlines.append(output) 51 52 return dict(more=more, output='\n'.join(outlines))
53
54 - def _process_request(self, line):
55 if len(self.console.buffer): 56 prompt = sys.ps2 57 else: 58 prompt = sys.ps1 59 60 myout = StringIO.StringIO() 61 62 output = "%s%s" % (prompt, line) 63 # hopefully Python doesn't interrupt in this block 64 # lest we'll get some curious output. 65 try: 66 sys.stdout = myout 67 sys.stderr = myout 68 more = self.console.push(line) 69 finally: 70 sys.stdout = sys.__stdout__ 71 sys.stderr = sys.__stderr__ 72 73 stdout = myout.getvalue() 74 75 if stdout: 76 output = '%s\n%s' % (output, stdout) 77 78 return more, output.rstrip()
79
80 - def new_console(self):
81 data = dict() 82 locs = dict(__name__='tg-admin', __doc__=None, 83 reload_console=self.new_console) 84 try: 85 mod = turbogears.util.get_model() 86 if mod: 87 locs.update(mod.__dict__) 88 except (pkg_resources.DistributionNotFound, ImportError): 89 import traceback 90 error = "Error: could not load data model.\n" 91 data['errors'] = [error] 92 error += traceback.format_exc() 93 log.warn(error) 94 self.console = InteractiveConsole(locals=locs) 95 return data
96 97 @expose('turbogears.toolbox.console')
98 - def index(self):
99 data = dict() 100 if not self.console: 101 data.update(self.new_console()) 102 return data
103